Spring Boot 與 Kotlin 定時任務(Scheduling Tasks)
阿新 • • 發佈:2019-02-01
在編寫Spring Boot應用中會遇到這樣的場景,比如:需要定時地傳送一些簡訊、郵件之類的操作,也可能會定時地檢查和監控一些標誌、引數等。
建立定時任務
在Spring Boot中編寫定時任務是非常簡單的事,下面通過例項介紹如何在Spring Boot中建立定時任務,實現每過5秒輸出一下當前時間。
在Spring Boot的主類中加入@EnableScheduling
註解,啟用定時任務的配置
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)
}
建立定時任務實現類
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("現在時間 , ${dateFormat.format(Date())}")
}
}
執行程式,控制檯中可以看到類似如下輸出,定時任務開始正常運作了。
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 : 現在時間 , 23:09:02
2018-01-21 23:09:03.042 INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現在時間 , 23:09:03
2018-01-21 23:09:04.042 INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現在時間 , 23:09:04
2018-01-21 23:09:05.042 INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks : 現在時間 , 23:09:05
@Scheduled詳解
在上面的入門例子中,使用了@Scheduled(fixedRate = 1000) 註解來定義每過1秒執行的任務,對於@Scheduled
的使用可以總結如下幾種方式:
- @Scheduled(fixedRate = 1000) :上一次開始執行時間點之後1秒再執行
- @Scheduled(fixedDelay = 1000) :上一次執行完畢時間點之後1秒再執行
- @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
- @Scheduled(cron=”/1 * * * *”) :通過cron表示式定義規則
@Scheduled 註解是單執行緒的,如果需要多執行緒,請增加@Async
更多Spring Boot 和 kotlin相關內容
歡迎關注公眾號《全棧架構》
全棧有風險,菜鳥需謹慎