在編寫Spring Boot應用中會遇到這樣的場景,比如:需要定時地發送一些短信、郵件之類的操作,也可能會定時地檢查和監控一些標誌、參數等。
創建定時任務
在Spring Boot中編寫定時任務是非常簡單的事,下面通過實例介紹如何在Spring Boot中創建定時任務,實現每過5秒輸出一下當前時間。
在Spring Boot的主類中加入@EnableScheduling註解,啟用定時任務的配置
import org.springframework.boot.SpringApplicationimport org.springframework.boot.autoconfigure.SpringBootApplicationimport org.springframework.scheduling.annotation.EnableScheduling/*** Created by http://quanke.name on 2018/1/12.*/@SpringBootApplication@EnableSchedulingclass Applicationfun main(args: Array<String>) {SpringApplication.run(Application::class.java, *args)}創建定時任務實現類
import org.apache.commons.logging.LogFactoryimport org.springframework.scheduling.annotation.Scheduledimport org.springframework.stereotype.Componentimport java.text.SimpleDateFormatimport java.util.*/*** Created by http://quanke.name on 2018/1/12.*/@Componentclass 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] nqkotlin.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] nqkchaper11_8_1.task.ScheduledTasks : 現在時間, 23:09:02
2018-01-21 23:09:03.042 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : 現在時間, 23:09:03
2018-01-21 23:09:04.042 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : 現在時間, 23:09:04
2018-01-21 23:09:05.042 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : 現在時間, 23:09:05
@Scheduled詳解
在上面的入門例子中,使用了@Scheduled(fixedRate = 1000) 註解來定義每過1秒執行的任務,對於@Scheduled的使用可以總結如下幾種方式:
@Scheduled 註解是單線程的,如果需要多線程,請增加@Async
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。