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

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

相关推荐
孫治AllenSun2 小时前
【LangChain4J-04】Tool 工具的使用
java·人工智能
choumou_M2 小时前
MySQL_1:数据库悲观锁
后端·spring·spring cloud
南城以南溫暖如初1472 小时前
树洞交友系统架构设计与匿名聊天实战指南
java·spring boot·mysql·系统架构·vue·mybatis·交友
lemon_sjdk2 小时前
JavaFX 响应式核心:从属性绑定、失效通知到生命周期管理
java
智码看视界3 小时前
Day60-Serverless:函数计算改写传统Spring Boot
spring boot·云原生·serverless·函数计算·冷启动
Lost of 程序猿3 小时前
ASP.NET Core SignalR 实战:从实时推送到底层协议与高可用部署
后端·asp.net
QCodingDev3 小时前
Spring AI Alibaba Graph实战:从ReAct Agent到Workflow,企业AI复杂流程该如何编排?
java·人工智能·spring·ai·ai编程·企业ai
一嘴一个橘子3 小时前
SpringDataRedis 操作 redis
java·redis
JasmineWr3 小时前
Spring BeanDefinition 与 Bean 生命周期、循环依赖解析
java·后端·spring
dzl843943 小时前
微服务基座
java