【Spring Boot】# 使用@Scheduled注解无法执行定时任务

1. 前言

在 Spring Boot中,使用@Scheduled注解来定义定时任务时,定时任务不执行;或未在规定时间执行。

java 复制代码
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MySchedule {

    /**
     * 5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void task1() {
        System.out.println("Scheduled task-1111 is running ... ...");
    }

    /**
     * 10秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void task2() {
        System.out.println("Scheduled task-2222 is running ... ...");
    }
}

2. 解决

2.1 定时任务不执行

  • 启动类 或者相关Configuration类上,添加@EnableScheduling注解;
  • 然后在定义定时任务的类上,添加 @Component 注解

2.2 未按规定时间执行

如果使用@Scheduled注解定义了多个定时任务,但是任务未按规定时间执行。

  • 增加配置类,改变线程池大小

    java 复制代码
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.SchedulingConfigurer;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
    import org.springframework.scheduling.config.ScheduledTaskRegistrar;
    
    /**
     * @Description : scheduler配置类
     */
    @Configuration
    public class ScheduledTaskConfig implements SchedulingConfigurer {
        @Override
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
            taskScheduler.setPoolSize(20); // 线程池大小设置为20
            taskScheduler.initialize();
            taskRegistrar.setTaskScheduler(taskScheduler);
        }
    }

原因分析

  • 查看 @Scheduled注解的源码:每一个有@Scheduled注解的方法都会被注册为一个ScheduledAnnotationBeanPostProcessor

  • 继续跟踪,看ScheduledAnnotationBeanPostProcessor的源码

    从图中的这句话得知,如果我们不主动配置我们需要的TaskScheduler,Spring Boot会默认使用一个单线程的scheduler来处理我们用@Scheduled注解实现的定时任务

要的TaskScheduler,Spring Boot会默认使用一个单线程的scheduler来处理我们用@Scheduled注解实现的定时任务

因为默认是单线程处理,因此就会导致有的有的任务在规定时间内没执行,需要等待。

相关推荐
Oneslide4 小时前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp4 小时前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒4 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569155 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
吃饱了得干活6 小时前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
神奇小汤圆6 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L7 小时前
LangGraph入门学习资料
后端
神奇小汤圆7 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
后端
kfaino7 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
lwx572807 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端