spring自帶的定時任務功能@EnableScheduling
阿新 • • 發佈:2018-08-04
The exec com 計劃執行 int ann format highlight read
1 demo
package com.test.domi.config; import org.springframework.beans.factory.annotation.Configurable; 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; @Component @Configurable @EnableScheduling public class ScheduledTasks { //每30秒執行一次 @Scheduled(fixedRate = 1000 * 30) public void reportCurrentTime(){ System.out.println ("Scheduling Tasks Examples: The time is now " + dateFormat ().format (new Date ())); } //在固定時間執行 @Scheduled(cron = "0 */1 * * * * ") public void reportCurrentByCron(){ System.out.println ("Scheduling Tasks Examples By Cron: The time is now " + dateFormat ().format (new Date())); } private SimpleDateFormat dateFormat(){ return new SimpleDateFormat ("HH:mm:ss"); } }
Scheduling Tasks Examples: The time is now 11:55:54 Scheduling Tasks Examples By Cron: The time is now 11:56:00 Scheduling Tasks Examples: The time is now 11:56:24 Scheduling Tasks Examples: The time is now 11:56:54 Scheduling Tasks Examples By Cron: The time is now 11:57:00
2 詳解
http://tramp.cincout.cn/2017/08/18/spring-task-2017-08-18-spring-boot-enablescheduling-analysis/
cron表達式:https://www.zhyd.me/article/43
3 總結
默認的 ConcurrentTaskScheduler 計劃執行器采用Executors.newSingleThreadScheduledExecutor() 實現單線程的執行器。因此,對同一個調度任務的執行總是同一個線程。如果任務的執行時間超過該任務的下一次執行時間,則會出現任務丟失,跳過該段時間的任務。上述問題有以下解決辦法:
采用異步的方式執行調度任務,配置 Spring 的 @EnableAsync,在任務執行的方法上標註 @Async配置任務執行池,采用 ThreadPoolTaskScheduler.setPoolSize(n)。 n 的數量為 單個任務執行所需時間 / 任務執行的間隔時間
spring自帶的定時任務功能@EnableScheduling