定時任務或者說定時調度,是系統中比較廣泛的一個功能,例如數據歸檔、清理,數據定時同步(非實時),定時收發等等都須要用到定時任務,常見的定時調度框架有Quartz、TBSchedule等。java
如何在Spring boot裏實現定時任務呢?spring
SpringBoot定時方式有不少種,我才用 @Scheduled 註解配置定時任務多線程
Spring自3.0版本起也增長了任務調度功能Schedule,它是一個輕量級的Quartz,使用起來方便、簡潔,且不須要依賴其餘的JAR包。框架
@EnableScheduling開啓計劃任務支持,在入口類中添加異步
@Scheduled計劃任務聲明,在具體方法中添加分佈式
eg:spa
package com.tydt.bim.common; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @EnableScheduling @Component @EnableAsync public class ScheduleSetting { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * fixedRate多久執行一次,單位:毫秒 * initialDelay 延遲容器啓動後執行,單位:毫秒 */ @Async @Scheduled(fixedRate = 10000,initialDelay = 2000) public void scheduleTest1(){ System.out.println("10s執行一次--->"+sdf.format(new Date())); } /** * fixedDelay在指定的時間執行一次,單位:毫秒 * 在建立後會執行一次,在第一次執行後,會每隔5S執行一次 */ @Async @Scheduled(fixedDelay = 5000) public void scheduleTest2(){ System.out.println("5s執行一次--->"+sdf.format(new Date())); } /** * cron表達式,下面表示,每隔20s執行一次,具體的能夠自行定義 */ @Async @Scheduled(cron = "0/20 * * * * ? ") public void scheduleTest3(){ System.out.println("20執行一次--->"+sdf.format(new Date())); } }
說明:線程
@Scheduled
參數能夠接受兩種定時的設置code
表示每隔五秒執行一次orm
(1)fixedRate = 5000
(2)cron =
"0/5 * * * * ? "
cron表達式
一個cron表達式有至少6個(也可能7個)有空格分隔的時間元素。按順序依次爲:
秒(0~59) 分鐘(0~59) 3 小時(0~23) 4 天(0~31) 5 月(0~11) 6 星期(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT) 年份(1970-2099) 其中每一個元素能夠是一個值(如6),一個連續區間(9-12),一個間隔時間(8-18/4)(/表示每隔4小時),一個列表(1,3,5),通配符。因爲」月份中的日期」和」星期中的日期」這兩個元素互斥的,必需要對其中一個設置。配置實
例:
/5 * * * ? 每隔5秒執行一次
0 /1 * * ? 每隔1分鐘執行一次
0 0 10,15,18 * * ? 天天上午10點,下午3點,6點
0 0 12 * * ? 天天中午12點觸發
0 15 10 * * ? * 天天上午10:15觸發
@EnableAsync開啓多線程
@Async標記其爲一個異步任務
注:
自帶的Schedule不支持分佈式部署