在SpringBoot中使用定時任務,用到了兩個註解:
1)、創建任務類
@Component@EnableSchedulingpublic class TaskWork { }
2)、多種定時機制
cron表達式:
一個cron表達式有至少6個(也可能7個)有空格分隔的時間元素。按順序依次為:
其中每個元素可以是一個值(如6),一個連續區間(9-12),一個間隔時間(8-18/4)(/表示每隔4小時),一個列表(1,3,5),通配符。由於」月份中的日期」和」星期中的日期」這兩個元素互斥的,必須要對其中一個設置。
關於Cron表達式介紹
cronExpression定義時間規則,Cron表達式由6或7個空格分隔的時間欄位組成:秒 分鐘 小時 日期 月份 星期 年(可選)
3)、實現定時任務 當一個任務的處理超時時,由於每個任務是單線程的,所以對於定時任務而言,有可能會延遲下一個任務。 當出現這種情況,就需要使用多線程定時任務,可以是使用下面註解來實現: 具體代碼如下:欄位 允許值 允許的特殊字符 秒 0-59 , - * / 分 0-59 , - * / 小時 0-23 , - * / 日期 1-31 , - * ? / L W C 月份 1-12 , - * / 星期 1-7 , - * ? / L C 3」 每月的第三個星期五上午10:15觸發
@Component@EnableSchedulingpublic class TaskWork { private int workCount = 0; /** * fixedRate 的單位是毫秒 */ @Scheduled(fixedRate = 1000) public void taskCounter() { workCount ++; System.out.println(&34; + workCount); } @Scheduled(cron = &34;) public void taskRun5() throws InterruptedException { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat(&34;); System.out.println(Thread.currentThread().getName()+&34;+ft.format(dNow)); }}
3、定時任務重入問題
package com.shenmazong.bootdemotask.task;import lombok.extern.slf4j.Slf4j;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.util.Date;@Slf4j@Component@EnableScheduling // 1.開啟定時任務@EnableAsync // 2.開啟多線程public class WorkTask { /** * TODO 每秒鐘執行一次任務 */ @Async @Scheduled(fixedRate = 1000) public void fixRateTask() { String strDateTime = new Date().toString(); try { Thread.sleep(1000*30); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+&34;+strDateTime); } /** * TODO 每5秒執行一次任務 */ @Scheduled(cron = &34;) public void fixTimeTask() {// String strDateTime = new Date().toString();//// try {// Thread.sleep(1000*10);// } catch (InterruptedException e) {// e.printStackTrace();// }//// System.out.println(Thread.currentThread().getName()+&34;+strDateTime); }}