【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注解实现的定时任务

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

相关推荐
妙码生花2 分钟前
从 PHP 到 AI + Golang,程序员自救转型手记(八):设计管理员模型、热重载配置
前端·后端·go
白鲸开源4 分钟前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
ServBay9 分钟前
拒绝当二等公民,Windows 开发者如何无痛开启 Claude Code 本地全栈运维?
后端·ai编程·mcp
用户342323237631722 分钟前
从数据源到仪表盘——全链路端到端实战整合
后端
Apifox41 分钟前
从 Postman 迁移到 Apifox:Workspace、Collection、Environment 现在可以一起导入了
前端·后端·程序员
用户7713970207062 小时前
深入解析 C# Path.ChangeExtension:原来改扩展名可以这么简单
后端
zimoyin2 小时前
深入理解 Kotlin 协程:从零实现一个 IO 优先 + 虚拟线程溢出的混合调度器
后端
雨落倾城夏未凉2 小时前
第四章c#方法-参数数组和可选参数(16)
后端·c#
陈随易4 小时前
VSCode古法神器fnMap v9开发故事
前端·后端·程序员