springboot整合定時任務(相對於Quartz和Task等框架非常簡單)
阿新 • • 發佈:2018-12-22
最近真正用springboot整合定時任務發現其流程灰常簡單,進一步突出了springboot的強大之處。相對於之前用過的quartz和task來說可以說是簡單爆了,尤其是quartz整合spirng的時候那配置簡直是日了動物園了。廢話不說直接懟程式碼。
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; //下邊這個註解可以不加,可以在任務類上邊加上也可以起到同樣的作用 @EnableScheduling @SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
package com.example.demo; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @Configurable //如果啟動類上加上了下邊這個註解在這裡就不要再加了。當然加了也不會報錯(親測)這裡我給註釋掉了 //@EnableScheduling public class ScheduleTask { //這裡的cron表示式意思是每隔10秒執行一次 @Scheduled(cron = "0/10 * * * * ? ") public void reportCurrentTime() { System.err.println("scheduling111 tasks example By corn the time is now:" + dateFormat().format(new Date())); } public SimpleDateFormat dateFormat() { return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } }
在這裡推薦一個關於cron表示式的網站,可以直接根據自己的需要來生成cron表示式。
最後如果您需要了解傳統的quartz定時框架,可以看一下我之前寫的兩篇部落格。
如果不嫌棄可以給博主點個贊吧,不嫌棄的話加個關注以此來共同學習。it嘛註定就在bug和新技術上游蕩。哈哈~~~~~~