首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring @Scheduled 定時任務完整指南:固定頻率、Cron 表達式、年份限制避坑

     編輯:Java 綜合教學

Spring @Scheduled 定時任務完整指南:固定頻率、Cron 表達式、年份限制避坑

Spring Task 提供輕量級定時調度,@Scheduled 支援固定延遲、固定頻率、Cron 表達式三種模式。本文詳解配置、用法、Cron 參數表、不支援年份字段的關鍵避坑。

1. 啟用配置

<beans xmlns:task="https://www.springframework.org/schema/task" ...>
    <task:executor id="executor" pool-size="10" queue-capacity="128"/>
    <task:scheduler id="scheduler" pool-size="10"/>
    <task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/>
</beans>

或 Java Config:@EnableScheduling + 自定義 TaskScheduler Bean。

2. 三種觸發模式

模式屬性含義示例
固定延遲fixedDelay上一次執行結束 → 間隔 N 毫秒 → 下一次開始@Scheduled(fixedDelay = 5000)
固定頻率fixedRate上一次執行開始 → 間隔 N 毫秒 → 下一次開始@Scheduled(fixedRate = 5000)
Cron 表達式cron複雜時間規則(秒 分 時 日 月 周)@Scheduled(cron = "0 0 2 * * ?")

3. Cron 表達式詳解(6 個字段)

秒(0-59) 分(0-59) 時(0-23) 日(1-31) 月(1-12) 周(1-7 或 SUN-SAT)
特殊符號含義示例
*所有值* * * * * * 每秒
?不指定值(日/周互斥)0 0 12 ? * * 每天中午
-範圍9-17 9點到17點
,列表MON,WED,FRI
/增量0/15 每15分鐘
L最後日:L 月最後一天,周:L 週六
W工作日15W 最近工作日
#第 N 個周X6#3 第3個週五

常用示例

0 0 12 * * ?           每天中午 12:00
0 15 10 ? * MON-FRI    工作日 10:15
0 0 12 ? * 6L          每月最後週六 12:00
0 15 10 ? * 6#3        每月第3個週五 10:15
0 0/5 14 * * ?         14:00-14:55 每5分鐘
0 0/5 14,18 * * ?      14點和18點各每5分鐘

4. 關鍵避坑:@Scheduled 不支援年份字段

Quartz Cron 支援 7 字段(含年),但 Spring CronSequenceGenerator 解析器強制要求 6 字段。

// 錯誤:7 字段會拋 IllegalStateException
@Scheduled(cron = "0 18 10 * * ? 2016-2016")

// 正確:6 字段
@Scheduled(cron = "0 18 10 * * ?")

源碼驗證:

String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
if (fields.length != 6) throw new IllegalArgumentException(
    "cron expression must consist of 6 fields (found " + fields.length + " in \"" + expression + "\")");

解決方案

  1. 業務層面:在任務方法內部判斷年份,不在範圍內直接 return。
  2. 框架層面:需年份級調度請改用 Quartz 或 Spring Quartz Scheduler。

最佳實踐建議

  1. 生產環境自定義線程池,避免默認單線程串行導致後續任務延遲。
  2. 任務方法捕獲異常並記錄日誌,防止異常導致調度器停止後續執行。
  3. 長耗時任務建議異步執行(@Async + 自定義執行器),避免佔用調度線程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved