springBoot(19):定时任务
一、依賴
| 1 2 3 4 | <dependency> ???<groupId>org.springframework.boot</groupId> ???<artifactId>spring-boot-starter</artifactId> </dependency> |
二、實(shí)現(xiàn)
啟動(dòng)類上需加上@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; /** ?*?每隔六秒執(zhí)行(cron表達(dá)式) ?* ?*?@Author:?我愛(ài)大金子 ?*?@Description:?每隔六秒執(zhí)行(cron表達(dá)式) ?*?@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; /** ?*?每隔六秒執(zhí)行(fixed方式) ?* ?*?@Author:?我愛(ài)大金子 ?*?@Description:?每隔六秒執(zhí)行(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("現(xiàn)在時(shí)間:"?+?dateFormat.format(new?Date())); ????} } |
效果:
?
三、說(shuō)明
3.1、@Scheduled參數(shù)
@Scheduled參數(shù)可以接受兩種定時(shí)的設(shè)置:一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內(nèi)容。
fixedRate說(shuō)明
?@Scheduled(fixedRate = 6000) :上一次開(kāi)始執(zhí)行時(shí)間點(diǎn)之后6秒再執(zhí)行
?@Scheduled(fixedDelay = 6000) :上一次執(zhí)行完畢時(shí)間點(diǎn)之后6秒再執(zhí)行
?@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每6秒執(zhí)行一次
3.2、Could not find default TaskScheduler bean異常處理
就會(huì)在debug級(jí)別的日志輸出一個(gè)異常:
| 1 | logger.debug("Could?not?find?default?TaskScheduler?bean",?ex); |
當(dāng)然,這個(gè)異常并不影響應(yīng)用程序運(yùn)行,如果你不想看到這個(gè)異常,就可以通過(guò)提升org.springframework.scheduling這個(gè)包下日志級(jí)別來(lái)屏蔽這個(gè)不合理的異常。
本文轉(zhuǎn)自我愛(ài)大金子博客51CTO博客,原文鏈接http://blog.51cto.com/1754966750/1944645如需轉(zhuǎn)載請(qǐng)自行聯(lián)系原作者
我愛(ài)大金子
總結(jié)
以上是生活随笔為你收集整理的springBoot(19):定时任务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SecureCRT的上传下载小技巧(Li
- 下一篇: 完美平方