前言
前幾節(jié)我們用第三方框架quarz實現(xiàn)了定時任務,實際上spring3.1開始,spring已經(jīng)內(nèi)置了定時任務的支持,實現(xiàn)非常簡單,下面我們一起看看怎么實現(xiàn)
參考項目:https://github.com/bigbeef/cppba-sample
開源地址:https://github.com/bigbeef
個人博客:http://blog.cppba.com
ScheduleApplication.java
其中重點是@EnableScheduling注解,表示啟動定時任務支持
package com.cppba;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class, args);
}
}
SaySchedule.java
package com.cppba.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SaySchedule {
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Scheduled(cron = "0/2 * * * * ?")
public void sayHi() {
System.out.println("hi! time is :" + df.format(new Date()));
}
@Scheduled(cron = "1/2 * * * * ?")
public void sayHello() {
System.out.println("hello! time is :" + df.format(new Date()));
}
}
核心重點是@Scheduled注解,@Scheduled支持多種類型的計劃任務:cron、fixDelay、fixRate,最流行的還是cron表達式,
在這里推薦一個cron表達式在線生成器:http://cron.qqe2.com/

功能很強大,可以圖形化配置cron表達式,也可以泛解析cron表達式的執(zhí)行時間,特別方便
運行項目
控制臺打印如下:
hi! time is :2017-08-22 22:40:08
hello! time is :2017-08-22 22:40:09
hi! time is :2017-08-22 22:40:10
hello! time is :2017-08-22 22:40:11
hi! time is :2017-08-22 22:40:12
hello! time is :2017-08-22 22:40:13
hi! time is :2017-08-22 22:40:14
hello! time is :2017-08-22 22:40:15
hi! time is :2017-08-22 22:40:16
hello! time is :2017-08-22 22:40:17
hi! time is :2017-08-22 22:40:18
hello! time is :2017-08-22 22:40:19
hi! time is :2017-08-22 22:40:20
hello! time is :2017-08-22 22:40:21
hi! time is :2017-08-22 22:40:22
hello! time is :2017-08-22 22:40:23
hi! time is :2017-08-22 22:40:24
hello和hi交替執(zhí)行,因為我們配置的cron表達式是:sayHi方法從0秒開始,每兩秒執(zhí)行一次;sayHello方法從1秒開始,每兩秒執(zhí)行一次。
到此,我們的定時任務運行成功!