本文章來自【知識林】
在定時(shí)任務(wù)中一般有兩種情況:
- 指定何時(shí)執(zhí)行任務(wù)
- 指定多長時(shí)間后執(zhí)行任務(wù)
這兩種情況在Springboot中使用Scheduled都比較簡單的就能實(shí)現(xiàn)了。
- 修改程序入口
@SpringBootApplication
@EnableScheduling
public class RootApplication {
public static void main(String [] args) {
SpringApplication.run(RootApplication.class, args);
}
}
在程序入口的類上加上注釋@EnableScheduling即可開啟定時(shí)任務(wù)。
- 編寫定時(shí)任務(wù)類
@Component
public class MyTimer {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 3000)
public void timerRate() {
System.out.println(sdf.format(new Date()));
}
}
在程序啟動后控制臺將每隔3秒輸入一次當(dāng)前時(shí)間,如:
23:08:48
23:08:51
23:08:54
注意: 需要在定時(shí)任務(wù)的類上加上注釋:@Component,在具體的定時(shí)任務(wù)方法上加上注釋@Scheduled即可啟動該定時(shí)任務(wù)。
下面描述下@Scheduled中的參數(shù):
@Scheduled(fixedRate=3000):上一次開始執(zhí)行時(shí)間點(diǎn)后3秒再次執(zhí)行;
@Scheduled(fixedDelay=3000):上一次執(zhí)行完畢時(shí)間點(diǎn)后3秒再次執(zhí)行;
@Scheduled(initialDelay=1000, fixedDelay=3000):第一次延遲1秒執(zhí)行,然后在上一次執(zhí)行完畢時(shí)間點(diǎn)后3秒再次執(zhí)行;
@Scheduled(cron="* * * * * ?"):按cron規(guī)則執(zhí)行。
下面貼出完整的例子:
package com.zslin.timers;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by 鐘述林 393156105@qq.com on 2016/10/22 21:53.
*/
@Component
public class MyTimer {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
//每3秒執(zhí)行一次
@Scheduled(fixedRate = 3000)
public void timerRate() {
System.out.println(sdf.format(new Date()));
}
//第一次延遲1秒執(zhí)行,當(dāng)執(zhí)行完后3秒再執(zhí)行
@Scheduled(initialDelay = 1000, fixedDelay = 3000)
public void timerInit() {
System.out.println("init : "+sdf.format(new Date()));
}
//每天23點(diǎn)27分50秒時(shí)執(zhí)行
@Scheduled(cron = "50 27 23 * * ?")
public void timerCron() {
System.out.println("current time : "+ sdf.format(new Date()));
}
}
在Springboot中使用Scheduled來做定時(shí)任務(wù)比較簡單,希望這個(gè)例子能有所幫助!
示例代碼:https://github.com/zsl131/spring-boot-test/tree/master/study11
本文章來自【知識林】