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

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

相关推荐
追逐时光者28 分钟前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
雨白30 分钟前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java
TF男孩33 分钟前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥2 小时前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
AAA修煤气灶刘哥2 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
你的人类朋友2 小时前
什么是API签名?
前端·后端·安全
昵称为空C4 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默5 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin5 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在6 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust