創(chuàng)建定時任務(wù)
在Spring Boot中編寫定時任務(wù)是非常簡單的事,下面通過實例介紹如何在Spring Boot中創(chuàng)建定時任務(wù),實現(xiàn)每過5秒輸出一下當(dāng)前時間。
- 在Spring Boot的主類中加入
@EnableScheduling
注解,啟用定時任務(wù)的配置
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 創(chuàng)建定時任務(wù)實現(xiàn)類
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("現(xiàn)在時間:" + dateFormat.format(new Date()));
}
}
- 運行程序,控制臺中可以看到類似如下輸出,定時任務(wù)開始正常運作了。
2016-05-15 10:40:04.073 INFO 1688 --- [ main] com.didispace.Application : Started Application in 1.433 seconds (JVM running for 1.967)
現(xiàn)在時間:10:40:09
現(xiàn)在時間:10:40:14
現(xiàn)在時間:10:40:19
現(xiàn)在時間:10:40:24
現(xiàn)在時間:10:40:29522
現(xiàn)在時間:10:40:34
關(guān)于上述的簡單入門示例也可以參見官方的Scheduling Tasksopen in new window
#@Scheduled詳解
在上面的入門例子中,使用了@Scheduled(fixedRate = 5000)
注解來定義每過5秒執(zhí)行的任務(wù),對于@Scheduled
的使用可以總結(jié)如下幾種方式:
@Scheduled(fixedRate = 5000)
:上一次開始執(zhí)行時間點之后5秒再執(zhí)行@Scheduled(fixedDelay = 5000)
:上一次執(zhí)行完畢時間點之后5秒再執(zhí)行@Scheduled(initialDelay=1000, fixedRate=5000)
:第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每5秒執(zhí)行一次@Scheduled(cron="*/5 * * * * *")
:通過cron表達(dá)式定義規(guī)則
#代碼示例
本文的相關(guān)例子可以查看下面?zhèn)}庫中的chapter4-1-1
目錄:
- Github:https://github.com/dyc87112/SpringBoot-Learningopen in new window
- Gitee:https://gitee.com/didispace/SpringBoot-Learning