SpringBoot非官方教程 | 第十八篇: 定時任務(Scheduling Tasks)

這篇文章將介紹怎麼通過spring去做調度任務。

構建工程

創建一個Springboot工程,在它的程序入口加上@EnableScheduling,開啓調度任務。

@SpringBootApplication
@EnableScheduling
public class SpringbootSchedulingTasksApplication {

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

創建定時任務

創建一個定時任務,每過5s在控制檯打印當前時間。

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

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

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

通過在方法上加@Scheduled註解,表明該方法是一個調度任務。

@Scheduled(fixedRate = 5000) :上一次開始執行時間點之後5秒再執行
@Scheduled(fixedDelay = 5000) :上一次執行完畢時間點之後5秒再執行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
@Scheduled(cron=” /5 “) :通過cron表達式定義規則,什麼是cro表達式,自行搜索引擎。

測試

啓動springboot工程,控制檯沒過5s就打印出了當前的時間。

2017-04-29 17:39:37.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:37
2017-04-29 17:39:42.671 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:42
2017-04-29 17:39:47.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:47
2017-04-29 17:39:52.675 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:52

總結

在springboot創建定時任務比較簡單,只需2步:

1.在程序的入口加上@EnableScheduling註解。
2.在定時方法上加@Scheduled註解。

參考資料

https://spring.io/guides/gs/s...

源碼下載

https://github.com/forezp/Spr...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章