日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springBoot(19):定时任务

發布時間:2025/7/14 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springBoot(19):定时任务 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、依賴

1 2 3 4 <dependency> ???<groupId>org.springframework.boot</groupId> ???<artifactId>spring-boot-starter</artifactId> </dependency>

二、實現

啟動類上需加上@EnableScheduling注解

SpringBootSchedulingApplication.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 package?com.example.demo; import?org.springframework.boot.SpringApplication; import?org.springframework.boot.autoconfigure.SpringBootApplication; import?org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public?class?SpringBootSchedulingApplication?{ ???public?static?void?main(String[]?args)?{ ??????SpringApplication.run(SpringBootSchedulingApplication.class,?args); ???} }

Task1.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package?com.example.demo.utils.task; import?org.springframework.scheduling.annotation.Scheduled; import?org.springframework.stereotype.Component; /** ?*?每隔六秒執行(cron表達式) ?* ?*?@Author:?我愛大金子 ?*?@Description:?每隔六秒執行(cron表達式) ?*?@Date:?Create?in?18:03?2017/7/4 ?*/ @Component public?class?Task1?{ ????private?int?count=0; ????@Scheduled(cron="*/6?*?*?*?*??") ????private?void?process(){ ????????System.out.println("this?is?scheduler?task?runing??"+(count++)); ????} }

Task2.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package?com.example.demo.utils.task; import?org.springframework.scheduling.annotation.Scheduled; import?org.springframework.stereotype.Component; import?java.text.SimpleDateFormat; import?java.util.Date; /** ?*?每隔六秒執行(fixed方式) ?* ?*?@Author:?我愛大金子 ?*?@Description:?每隔六秒執行(fixed方式) ?*?@Date:?Create?in?18:03?2017/7/4 ?*/ @Component public?class?Task2?{ ????private?static?final?SimpleDateFormat?dateFormat?=?new?SimpleDateFormat("HH:mm:ss"); ????@Scheduled(fixedRate?=?6000) ????public?void?reportCurrentTime()?{ ????????System.out.println("現在時間:"?+?dateFormat.format(new?Date())); ????} }


效果:

?

三、說明

3.1、@Scheduled參數

@Scheduled參數可以接受兩種定時的設置:一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內容。

fixedRate說明

?@Scheduled(fixedRate = 6000) :上一次開始執行時間點之后6秒再執行

?@Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之后6秒再執行

?@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執行,之后按fixedRate的規則每6秒執行一次


3.2、Could not find default TaskScheduler bean異常處理

就會在debug級別的日志輸出一個異常:

1 logger.debug("Could?not?find?default?TaskScheduler?bean",?ex);

當然,這個異常并不影響應用程序運行,如果你不想看到這個異常,就可以通過提升org.springframework.scheduling這個包下日志級別來屏蔽這個不合理的異常。

本文轉自我愛大金子博客51CTO博客,原文鏈接http://blog.51cto.com/1754966750/1944645如需轉載請自行聯系原作者


我愛大金子

總結

以上是生活随笔為你收集整理的springBoot(19):定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。