在編寫Spring Boot應(yīng)用中會(huì)遇到這樣的場景,比如:需要定時(shí)地發(fā)送一些短信、郵件之類的操作,也可能會(huì)定時(shí)地檢查和監(jiān)控一些標(biāo)志、參數(shù)等。
創(chuàng)建定時(shí)任務(wù)
在Spring Boot中編寫定時(shí)任務(wù)是非常簡單的事,下面通過實(shí)例介紹如何在Spring Boot中創(chuàng)建定時(shí)任務(wù),實(shí)現(xiàn)每過5秒輸出一下當(dāng)前時(shí)間。
在Spring Boot的主類中加入@EnableScheduling注解,啟用定時(shí)任務(wù)的配置
1
2
3
4
5
6
7
8
9
10
11
12
|
import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.scheduling.annotation.EnableScheduling /** * Created by http://quanke.name on 2018/1/12. */ @SpringBootApplication @EnableScheduling class Application fun main(args: Array<String>) { SpringApplication.run(Application:: class .java, *args) } |
創(chuàng)建定時(shí)任務(wù)實(shí)現(xiàn)類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import org.apache.commons.logging.LogFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.text.SimpleDateFormat import java.util.* /** * Created by http://quanke.name on 2018/1/12. */ @Component class ScheduledTasks { val log = LogFactory.getLog(ScheduledTasks:: class .java)!! private val dateFormat = SimpleDateFormat(“HH:mm:ss”) @Scheduled (fixedRate = 1000 ) fun reportCurrentTime() { log.info(“現(xiàn)在時(shí)間 , ${dateFormat.format(Date())}”) } } |
運(yùn)行程序,控制臺(tái)中可以看到類似如下輸出,定時(shí)任務(wù)開始正常運(yùn)作了。
2018-01-21 23:09:01.112 INFO 23832 — [ main] n.q.kotlin.chaper11_8_1.ApplicationKt : Started ApplicationKt in 8.024 seconds (JVM running for 8.724)
2018-01-21 23:09:02.112 INFO 23832 — [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現(xiàn)在時(shí)間 , 23:09:02
2018-01-21 23:09:03.042 INFO 23832 — [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現(xiàn)在時(shí)間 , 23:09:03
2018-01-21 23:09:04.042 INFO 23832 — [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現(xiàn)在時(shí)間 , 23:09:04
2018-01-21 23:09:05.042 INFO 23832 — [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現(xiàn)在時(shí)間 , 23:09:05
@Scheduled詳解
在上面的入門例子中,使用了@Scheduled(fixedRate = 1000) 注解來定義每過1秒執(zhí)行的任務(wù),對(duì)于@Scheduled的使用可以總結(jié)如下幾種方式:
- @Scheduled(fixedRate = 1000) :上一次開始執(zhí)行時(shí)間點(diǎn)之后1秒再執(zhí)行
- @Scheduled(fixedDelay = 1000) :上一次執(zhí)行完畢時(shí)間點(diǎn)之后1秒再執(zhí)行
- @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每5秒執(zhí)行一次
- @Scheduled(cron=”/1 “) :通過cron表達(dá)式定義規(guī)則
@Scheduled 注解是單線程的,如果需要多線程,請(qǐng)?jiān)黾覢Async
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.shumulu.com/archives/133739