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):定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SecureCRT的上传下载小技巧(Li
- 下一篇: 完美平方