前言
Spring Boot提供了@EnableScheduling
和 @Scheduled
注解,用於支持定時任務的執行,那么接下來就讓我們學習下如何使用吧;
假設我們需要每隔10秒執行一個任務,那么我們可以按一下步驟來完成開發;
添加@EnableScheduling注解
在Spring Boot的啟動類上添加@EnableScheduling
注解,@EnableScheduling
屬於Spring Context 模塊的注解,其內部通過@Import(SchedulingConfiguration.class)
注解引入了SchedulingConfiguration
;
添加注解代碼示例如下:
@SpringBootApplication
@EnableScheduling
public class SpringBootWebApplication {
}
添加@Scheduled注解
接下來我們就可以在需要執行定時任務的方法上添加@Scheduled
注解了,前提條件是該方法不能有參數;
對於每一個沒有參數的方法,添加@Scheduled
注解后,都會被默認的線程池按計划執行;
代碼示例:
@Scheduled(initialDelay = 1000, fixedRate = 10000)
public void run() {
logger.info("Current time is :: " + Calendar.getInstance().getTime());
}
控制台輸出:
2017-03-08 15:02:55 - Current time is :: Wed Mar 08 15:02:55 IST 2017
2017-03-08 15:03:05 - Current time is :: Wed Mar 08 15:03:05 IST 2017
2017-03-08 15:03:15 - Current time is :: Wed Mar 08 15:03:15 IST 2017
2017-03-08 15:03:25 - Current time is :: Wed Mar 08 15:03:25 IST 2017
2017-03-08 15:03:35 - Current time is :: Wed Mar 08 15:03:35 IST 2017