一、SpringBoot開啓定時任務
SpringBoot零配置開啓定時任務,有兩種情況:
- 在啓動類添加註解@EnableScheduling
- 在指定的配置類上添加註解@EnableScheduling
如果定時任務全部提取成一個項目,建議在啓動類上面添加註解;如果某個項目中有個別定時任務,那麼只需要在指定的類上面添加註解即可。
代碼如下:
@Configuration
@EnableScheduling
public class SongsirDemoJob {
private static final Logger log = LoggerFactory.getLogger(SongsirDemoJob.class);
// 每30秒執行一次
@Scheduled(cron = "*/30 * * * * ?")
public void work() {
long start = System.currentTimeMillis();
log.info("\r\n***************開始執行定時任務*****************");
// doSomething
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("耗時:" + (System.currentTimeMillis() - start));
log.info("\r\n***************定時任務結束*****************\n\n\n");
}
}
執行效果如下:
上面使用了Cron表達式,下面簡單介紹一下。
二、Cron表達式
- cron表達式由6個或者7個域組成,中間由空格隔開
- 6個域分別表示 Seconds Minutes Hours DayofMonth Month DayofWeek
- 7個域分別表示 Seconds Minutes Hours DayofMonth Month DayofWeek Year
- 其中*表示任意值,比如在Minutes使用 *,表示任意分鐘都執行, */2表示每兩分鐘執行一次, */30每30分鐘執行一次
- 上面定時任務我使用了 */30 * * * * ?,即表示每30秒執行一次。
具體請參考博文:https://www.cnblogs.com/junrong624/p/4239517.html
其中Cron表達式配置與反解析請使用:
http://cron.qqe2.com/