You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot中配置Cron任务在指定时段每5分钟执行

修改Spring Boot定时任务Cron表达式实现时间范围限制

你需要调整Cron表达式,让任务仅在9:30-17:30之间每5分钟执行一次,单个Cron表达式无法精准规避17:35及之后的时间,可通过多个定时规则组合实现:

修改后的代码

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import java.time.LocalDateTime;

// 确保类上已添加@EnableScheduling注解开启定时功能
public class ScheduledTask {

    @Schedules({
        // 9点的30、35、40、45、50、55分执行
        @Scheduled(cron = "0 30/5 9 * * ?"),
        // 10点到16点,每5分钟执行一次(0、5、10...55分)
        @Scheduled(cron = "0 */5 10-16 * * ?"),
        // 17点的0、5、10、15、20、25、30分执行
        @Scheduled(cron = "0 0-30/5 17 * * ?")
    })
    public void runEvery5Minutes() {
        System.out.println("Current time is :: " + LocalDateTime.now());
    }
}

各Cron表达式说明

Cron表达式结构为:秒 分 时 日 月 周 年(可选)

  • 0 30/5 9 * * ?:秒固定为0,分钟从30开始每5分钟触发一次,限定小时为9
  • 0 */5 10-16 * * ?:秒固定为0,分钟每5分钟触发一次,限定小时范围为10到16
  • 0 0-30/5 17 * * ?:秒固定为0,分钟从0到30每5分钟触发一次,限定小时为17

组合后,任务会严格在9:30、9:35...9:55,10:00、10:05...16:55,17:00、17:05...17:30这些时间点执行,完全匹配需求。

内容的提问来源于stack exchange,提问作者Sivaram Chintalapudi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 22:42:36