當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot中使用@Scheduled创建定时任务
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot中使用@Scheduled创建定时任务
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
我們在編寫Spring Boot應(yīng)用中經(jīng)常會遇到這樣的場景,比如:我需要定時地發(fā)送一些短信、郵件之類的操作,也可能會定時地檢查和監(jiān)控一些標(biāo)志、參數(shù)等。
創(chuàng)建定時任務(wù)
在Spring Boot中編寫定時任務(wù)是非常簡單的事,下面通過實(shí)例介紹如何在Spring Boot中創(chuàng)建定時任務(wù),實(shí)現(xiàn)每過5秒輸出一下當(dāng)前時間。
- 在Spring Boot的主類中加入@EnableScheduling注解,啟用定時任務(wù)的配置
public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } |
- 創(chuàng)建定時任務(wù)實(shí)現(xiàn)類
public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); (fixedRate = 5000) public void reportCurrentTime() { System.out.println("現(xiàn)在時間:" + dateFormat.format(new Date())); } } |
- 運(yùn)行程序,控制臺中可以看到類似如下輸出,定時任務(wù)開始正常運(yùn)作了。
關(guān)于上述的簡單入門示例也可以參見官方的Scheduling Tasks
@Scheduled詳解
在上面的入門例子中,使用了@Scheduled(fixedRate = 5000) 注解來定義每過5秒執(zhí)行的任務(wù),對于@Scheduled的使用可以總結(jié)如下幾種方式:
- @Scheduled(fixedRate = 5000) :上一次開始執(zhí)行時間點(diǎn)之后5秒再執(zhí)行
- @Scheduled(fixedDelay = 5000) :上一次執(zhí)行完畢時間點(diǎn)之后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-Learning
- Gitee:https://gitee.com/didispace/SpringBoot-Learning
如果您覺得本文不錯,歡迎Star支持,您的關(guān)注是我堅持的動力!
總結(jié)
以上是生活随笔為你收集整理的Spring Boot中使用@Scheduled创建定时任务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java多线程系列(六):深入详解Syn
- 下一篇: 使用Cloud Studio在线编写、调