Spring Boot EP 19:Scheduling Tasks任務排程器
What Is Scheduling Tasks
前幾篇文章分享的都是與API相關的內容,算是即時類的服務,不過,一套完整的系統多少都會有一些批次形式的需求,雖然市面上有很多任務排程器的開發套件,若是遇到不複雜的功能,殺雞不需要用到牛刀吧!此時Spring Boot的Scheduking Tasks套件就非常的適合,不僅開發上非常的簡單,而且架構不複雜、易於維護與管理,重點是,語法與Spring Boot其他套件有一致的風格,第一次就能上手!
Spring官方說明:連結
實作
建立排程器的Class
步驟1:新創一個名為”Schedulings”的資料夾,並新增”DequeueTasks.java”檔案,如下圖:
步驟2:宣告幾個不同的函數,每個函數就是一個不同獨立任務。
package stockmarket.jovepater.com.stockmarket.Schedulings;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class DequeueTasks {
TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");
@Scheduled(fixedDelay = 60000, zone = "timeZone")
public void TaskDequeueFixedDelay() {
// do dequeue...
}
@Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES)
public void TaskDequeueFixedRate() {
// do dequeue...
}
@Scheduled(initialDelay = 600000)
public void TaskDequeueInitialDelay() {
// do dequeue...
}
@Scheduled(cron = "0 1 0 0 0 1/5")
public void TaskDequeueCron() {
// do dequeue...
}
}
排程器的種類
由上述程式碼可以發現Scheduling Tasks有多種”@Scheduled”可以用,並搭配不同的參數有不同的效果,如下:
- fixedDelay:上一次與下一次執行任務時間的差距,不管任務執行時間
- fixedRate:多久執行一次任務,不論上一個任務有沒有結束
- initialDelay:延遲多久後第一次執行任務
- cron:使用cron表示法來定義任務的執行頻率
- zone:指定時區,未指定時,預設為伺服器的時區
- timeUnit:指定時間最小需間,預設為ms
啟動排程器
透過加註@EnableScheduling的方式啟動排程器。
package stockmarket.jovepater.com.stockmarket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
// 透過加註@EnableScheduling啟動排程器
@EnableScheduling
@SpringBootApplication
public class StockmarketApplication {
public static void main(String[] args) {
SpringApplication.run(StockmarketApplication.class, args);
}
}
~ END ~