SpringBoot默認已經實現了定時任務。
啓動類啓用定時
在啓動類上面加上@EnableScheduling即可開啓定時。
package com.wu.parker.schedule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author: wusq
* @date: 2019/1/10
*/
@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class, args);
}
}
創建定時任務實現類
package com.wu.parker.schedule.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author: wusq
* @date: 2019/1/10
*/
@Component
public class MyTask {
@Scheduled(cron="*/6 * * * * ?")
private void execute(){
System.out.println("每6秒執行一次");
}
}
@Scheduled 參數可以接受兩種定時的設置,一種是我們常用的cron="*/6 * * * * ?",一種是fixedRate=6000,兩種都表示每隔六秒打印一下內容。
cron用法比較通用,目前看到的講得好的資料是《Spring 3.x企業應用開發實戰》第13章-任務調度和異步執行器。
源代碼
https://github.com/wu-boy/parker.git
parker-schedule模塊