本文章來(lái)自【知識(shí)林】
在定時(shí)任務(wù)中一般有兩種情況:
- 指定何時(shí)執(zhí)行任務(wù)
- 指定多長(zhǎng)時(shí)間后執(zhí)行任務(wù)
這兩種情況在Springboot中使用Scheduled都比較簡(jiǎn)單的就能實(shí)現(xiàn)了姿鸿。
- 修改程序入口
@SpringBootApplication
@EnableScheduling
public class RootApplication {
public static void main(String [] args) {
SpringApplication.run(RootApplication.class, args);
}
}
在程序入口的類上加上注釋@EnableScheduling
即可開(kāi)啟定時(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()));
}
}
在程序啟動(dòng)后控制臺(tái)將每隔3秒輸入一次當(dāng)前時(shí)間无午,如:
23:08:48
23:08:51
23:08:54
注意: 需要在定時(shí)任務(wù)的類上加上注釋:@Component
恨胚,在具體的定時(shí)任務(wù)方法上加上注釋@Scheduled
即可啟動(dòng)該定時(shí)任務(wù)。
下面描述下@Scheduled
中的參數(shù):
@Scheduled(fixedRate=3000)
:上一次開(kāi)始執(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來(lái)做定時(shí)任務(wù)比較簡(jiǎn)單合住,希望這個(gè)例子能有所幫助绰精!
示例代碼:https://github.com/zsl131/spring-boot-test/tree/master/study11
本文章來(lái)自【知識(shí)林】