SpringBoot使用@Scheduled定時器的示例詳解
@Scheduled注解是 Spring Boot 提供的定時任務配置工具,用于控制任務執(zhí)行時間。
使用方法:
- 先啟用定時器配置,添加注解@EnableScheduling,可在@SpringBootApplication或者@Configuration或者@Component等spring能夠掃描到的地方;
- 在spring能夠識別的類中定義沒有返回值和參數(shù)的方法,在方法上使用@Scheduled注解;
@Scheduled注解的參數(shù)解釋:
- fixedRate:固定速率(ms),按照每次任務的開始時間間隔執(zhí)行(定時器啟動的時候每次開始時間就已確定),上一次任務執(zhí)行時間超過后面的任務開始時間,后面任務會積壓到隊列里,等這個時間很長的任務結束后,隊列里的積壓任務全部同時放行;
- fixedRateString:同上,字符串類型,支持${}占位符,可靈活配置;
- fixedDelay:固定延遲(ms),以上次的結束時間開始延遲一定時間執(zhí)行下一次,不會積壓;
- fixedDelayString:同上,字符串類型,支持${}占位符,可靈活配置;
- initialDelay:延遲啟動定時器時間(ms),指定一段時間后才開始啟動定時器;
- initialDelayString:同上,字符串類型,支持${}占位符,可靈活配置;
- cron:cron表達式,比上面的更靈活,字符串類型,支持${}占位符,上次任務如果超時會自動丟棄當前時間應該執(zhí)行的任務;(跟linux的cron稍有區(qū)別,linux的是“分時日月周”,這個是“秒分時日月周[年]”,多了秒和可省略的年)
- zone:時區(qū),一般默認即可,自動使用服務器時區(qū),也可指定如“Asia/Shanghai”;
PS:占位符可以只占String的一部分;定時器里如果拋出異常不會影響下一次任務;對cron的簡單理解,可以把每個字段的設置都解釋為一個整數(shù)數(shù)組,例如在秒字段上的0/10,可以解釋成[0, 10, 20, 30, 40, 50],在月字段上的*表示所有值,可解釋成[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],也就是每個月都有;
測試代碼:
啟動類:
package testspringschedule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class TestSpringSchedule {
public static void main(String[] args) {
System.out.println("main start");
SpringApplication.run(TestSpringSchedule.class, args);
}
}測試fixedRate:
package testspringschedule;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
//@Configuration
@Component
//@EnableScheduling
public class MyRateSchedule {
@Scheduled(fixedRate = 5000, initialDelay = 3000, zone = "Asia/Shanghai")
// @Scheduled(fixedRateString = "5000", initialDelayString = "3000")
// @Scheduled(fixedRateString = "${abc:5}000", initialDelayString = "${def:3000}")
public void test1() {
System.out.println("fixedRate start:" + new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("fixedRate stop:" + new Date());
}
private int i = 0;
// @Scheduled(fixedRate = 1000, initialDelay = 3000)
public void test2() {
System.out.println("fixedRate start:" + new Date());
i++;
System.out.println(i);
if (i == 5) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("fixedRate stop:" + new Date());
}
}test1()執(zhí)行結果,開始時間都是間隔5s:

test2()執(zhí)行結果,開始時間間隔1s,超時積壓多個任務等上一個任務結束后全部同時執(zhí)行;

測試fixedDelay:
package testspringschedule;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyDelaySchedule {
@Scheduled(fixedDelay = 5000, initialDelay = 3000)
public void test1() {
System.out.println("fixedDelay start:" + new Date());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("fixedDelay stop:" + new Date());
}
}執(zhí)行結果:

測試cron:
package testspringschedule;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyCronSchedule {
@Scheduled(cron = "50/2 * * * * ?")
// @Scheduled(cron = "${s:1/2 * * * * ?}")
// @Scheduled(cron = "${s:0/5} * * * * ?")
public void test1() {
System.out.println("cron:" + new Date());
}
// @Scheduled(cron = "0/10 * * * * ?")
public void test2() {
System.out.println("cron start:" + new Date());
try {
Thread.sleep(11000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("cron stop:" + new Date());
}
}test1()執(zhí)行結果:

test2()執(zhí)行結果,超時丟棄:

也可以實現(xiàn)SchedulingConfigurer接口,使用配置類進行線程池、異常處理、拒絕策略等的一些配置:(默認配置所有定時器都是單線程串行的)
package testspringschedule;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.util.ErrorHandler;
@Configuration
public class MyScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(50);
taskScheduler.setThreadGroupName("Scheduled-Group");
taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
taskScheduler.setErrorHandler(new ErrorHandler() {
@Override
public void handleError(Throwable t) {
System.out.println("發(fā)生未捕獲異常:");
t.printStackTrace();
}
});
taskScheduler.initialize();
taskRegistrar.setTaskScheduler(taskScheduler);
}
}到此這篇關于SpringBoot使用@Scheduled定時器的文章就介紹到這了,更多相關SpringBoot @Scheduled定時器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- springboot使用定時器@Scheduled不管用的解決
- 使用springboot時,解決@Scheduled定時器遇到的問題
- SpringBoot中@Scheduled實現(xiàn)服務啟動時執(zhí)行一次
- 如何解決SpringBoot定時任務報錯Unexpected error occurred in scheduled task問題
- SpringBoot使用@Scheduled實現(xiàn)定時任務的并行執(zhí)行
- Springboot中@scheduled注解解析
- SpringBoot中@Scheduled()注解以及cron表達式詳解
- SpringBoot通過@Scheduled實現(xiàn)定時任務及單線程運行問題解決
- SpringBoot?ScheduledTaskRegistrar解決動態(tài)定時任務思路詳解
- 解決SpringBoot中的Scheduled單線程執(zhí)行問題
相關文章
Plugin ‘org.springframework.boot:spring-boot-maven-plug
這篇文章給大家介紹了Plugin ‘org.springframework.boot:spring-boot-maven-plugin:‘ not found的解決方案,親測可用,文中給出了兩種解決方法,需要的朋友可以參考下2024-01-01
springboot加載一個properties文件轉換為map方式
這篇文章主要介紹了springboot加載一個properties文件轉換為map方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
Spring Boot 2.x 實現(xiàn)文件上傳功能
這篇文章主要介紹了Spring Boot 2.x 實現(xiàn)文件上傳功能,本文分步驟通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
idea使用外置tomcat配置springboot詳細步驟
昨天小編遇到一個問題使用springboot自帶的tomcat啟動沒有任何問題,不知道idea使用外置tomcat配置springboot該如何設置的,今天小編給大家分享一篇教程幫助大家解決這個問題2021-07-07
詳解spring Boot 集成 Thymeleaf模板引擎實例
本篇文章主要介紹了spring Boot 集成 Thymeleaf模板引擎實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
Spring使用@Retryable實現(xiàn)自動重試機制
在微服務架構中,服務之間的調(diào)用可能會因為一些暫時性的錯誤而失敗,例如網(wǎng)絡波動、數(shù)據(jù)庫連接超時或第三方服務不可用等,在本文中,我們將介紹如何在 Spring 中使用 @Retryable 實現(xiàn)自動重試機制,需要的朋友可以參考下2025-01-01

