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

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

相关推荐
张明君644511 分钟前
在 Astro SSR 项目中实现服务启动前初始化
前端·后端
用户9338104348454 分钟前
MyBatis-Plus LambdaQueryWrapper 隐式转换踩坑:不知不觉索引失效
java
她的男孩8 分钟前
设计器能拖抄送,一点发布却报 flowable-servicetask-invalid-type:Forge Admin 部署前改写节点属性
spring boot·低代码·工作流引擎
用户37215742613511 分钟前
Java 在 PDF 中查找关键词:获取页码和坐标,并高亮匹配结果
java
用户37215742613517 分钟前
Java 删除 Excel 重复行:整行去重、按单列和多列去重
后端
Forget the Dream37 分钟前
Spring AI 2.0 系列(三):ChatClient 与 ChatModel:Spring AI 2.0 的两层职责
java·人工智能·spring·springai
AI入职记1 小时前
RAG 一个请求吃掉 8 个核,chat 只要 0.16 个
后端·ai编程
aurora_zjj1 小时前
Nginx $request_length 为什么会变成负数?一次流量统计异常的源码排查
后端
旋律4141 小时前
布隆过滤器(Bloom Filter)
后端
站大爷IP1 小时前
Python的构造方法把我坑惨了,原来__new__和__init__的区别这么大
后端