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

需求:每日11:00-23:00每20分钟执行的Spring Scheduler任务

Spring Scheduler 定时任务配置:每日11:00-23:00每20分钟执行一次

核心方案:使用Cron表达式

Spring Scheduler支持Cron表达式定义复杂定时规则,针对你的需求,对应的Cron表达式为:0 */20 11-23 * * ?

步骤1:开启定时任务功能

在Spring Boot启动类上添加@EnableScheduling注解,启用定时任务模块:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

步骤2:编写定时任务类

创建Spring管理的组件类,用@Scheduled注解标记任务方法:

硬编码Cron表达式方式

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class DailyTask {

    // 每日11:00至23:00期间,每20分钟执行一次
    @Scheduled(cron = "0 */20 11-23 * * ?")
    public void runTask() {
        // 在这里实现你的业务逻辑
        System.out.println("定时任务执行:" + System.currentTimeMillis());
    }
}

配置文件读取方式(推荐,便于修改)

在application.yml中配置Cron表达式:

spring:
  scheduling:
    tasks:
      cron:
        daily-task: "0 */20 11-23 * * ?"

然后在任务类中引用配置:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class DailyTask {

    @Scheduled(cron = "${spring.scheduling.tasks.cron.daily-task}")
    public void runTask() {
        // 业务逻辑实现
        System.out.println("定时任务执行:" + System.currentTimeMillis());
    }
}

Cron表达式解析

0 */20 11-23 * * ?各部分含义:

  • 0:秒位,指定在整分的第0秒执行
  • */20:分位,每20分钟触发一次(0分、20分、40分)
  • 11-23:小时位,覆盖上午11点到晚上11点的所有小时
  • *:日位,每天都执行
  • *:月位,每个月都执行
  • ?:周位,不指定星期(避免与日位规则冲突)

额外注意事项

  • 如果服务部署在非东八区服务器,可通过@Scheduled的zone属性指定时区,例如:@Scheduled(cron = "0 */20 11-23 * * ?", zone = "Asia/Shanghai")
  • 任务方法需为无参、无返回值;如需异步执行,可结合@Async注解使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:45:44