springboot @Scheduled创建定时任务七

2018-04-25  本文已影响80人  AmeeLove

创建定时任务

在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置


@SpringBootApplication
@EnableScheduling
public class Chapter02Application {

    public static  void main(String [] args){
        SpringApplication.run(Chapter02Application.class, args);

    }
}

image.png

创建定时任务实现类

@Component
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("reportCurrentTime 现在时间:" + dateFormat.format(new Date()));
    }

    @Scheduled(fixedDelay=8000)
    public void delayCurrentTime() {
        System.out.println("delayCurrentTime 现在时间: " + dateFormat.format(new Date()));
    }


    @Scheduled(cron = "*/10 * * * * ?")
    public void cronCurrentTime() {
        System.out.println("cronCurrentTime 现在时间  :" + dateFormat.format(new Date()));
    }
}

image.png
cronCurrentTime 现在时间  :12:26:10
reportCurrentTime 现在时间:12:26:10
delayCurrentTime 现在时间: 12:26:13
reportCurrentTime 现在时间:12:26:15
cronCurrentTime 现在时间  :12:26:20
reportCurrentTime 现在时间:12:26:20
delayCurrentTime 现在时间: 12:26:21
reportCurrentTime 现在时间:12:26:25
delayCurrentTime 现在时间: 12:26:29
cronCurrentTime 现在时间  :12:26:30
reportCurrentTime 现在时间:12:26:30
上一篇下一篇

猜你喜欢

热点阅读