SpringBoot定時任務Schedule使用
阿新 • • 發佈:2018-11-09
在開發中很多時候會用到定時任務, 以前用自定義類繼承TimerTask
public class CustomTask extends TimerTask{
@Override
public void run() {
// 執行業務程式碼
}
}
class Main {
public static void main(String[] args) {
// 呼叫
Timer timer= new Timer();
Calendar calendar= Calendar.getInstance(); // 設定定時時間, 當然還有其他方式
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.scheduleAtFixedRate(new CustomTask(),
timer.getTime(), 1000 * 60 * 10);
}
}
Timer和TimerTask詳解:https://blog.csdn.net/xieyuooo/article/details/8607220
下面進入正題, SpringBoot中優雅使用定時任務
- 新增支援
在SpringBoot的啟動類①中添加註解 @EnableScheduling
@SpringBootApplication
@EnableScheduling // ①
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 使用定時任務
/**
* 檢查小時均值報警
*/
@Scheduled(cron = "0 1 * * * *" )
public void overproofAlert() {
log.info("-----開始執行定時任務-----");
}
通過上面這一個註解 @Scheduled(cron = “0 1 * * “) 這樣就可以開啟定時任務了, 驚不驚喜!
Cron表示式說明 詳細說明
Cron是字串表示式, 並由’域’和空格組成。
模版: Seconds Minutes Hours DayOfMonth Month DayOfWeek Year
Year可選
各
Sencods
這樣建立的定時任務是同步的,即順序執行。 這會遇到一個問題,當某個任務中斷後會阻塞掉後面的任務, 導致其他任務‘失效’。所以配置非同步是非常有必要的, 步驟如下:
- 新增Config
@Configuration
@EnableAsync // ① 添加註解
public class AsyncConfig {
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(200);
executor.setQueueCapacity(10);
executor.initialize();
return executor;
}
}
- 在定時方法上新增 @Async 註解
@Scheduled(cron = "0 0/1 * * * *")
@Async // ②
public void oneMinuteTask() {
log.info("-----開始執行定時任務-----");
}