springboot定时任务@Scheduled执行多次的问题

目录
  • springboot定时任务@Scheduled执行多次
    • 原因
    • 解决方法
  • 使用 @Scheduled 定时任务突然不执行了

springboot定时任务@Scheduled执行多次

在spring boot开发定时任务时遇到一个很怪异的现象..我进行调试模式,在没有bug的情况下.执行了三 次才停止..如图:

原因

是因为执行时间太短,在CronSequenceGenerator.class的next方法。

public Date next(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTimeZone(this.timeZone);
        calendar.setTime(date);
        //1.设置下次执行时间的毫秒为0,如上次任务执行过程不足1秒,则calendar的时间会被设置成上次任务的执行时间
        calendar.set(14, 0);
        long originalTimestamp = calendar.getTimeInMillis();
        this.doNext(calendar, calendar.get(1));
        //2.由于有上面一步,执行时间太短,会导致下述条件为true
            if(calendar.getTimeInMillis() == originalTimestamp) {
        //3.calendar在原来的时间上增加1秒
            calendar.add(13, 1);
         //CronSequenceGenerator的doNext算法从指定时间开始(包括指定时间)查找符合cron表达式规则下一个匹配的时间
         //注意第一个匹配符是*,由于增加了1秒,依然符合cron="* 0/2 * * * *",所以下一个执行时间就是在原来的基础上增加了一               秒
            this.doNext(calendar, calendar.get(1));
        }
        return calendar.getTime(); 

代码会进入if语句,并设置执行时间在原来的基础上增加一秒。

但由于增加一秒后的时间戳依然符合cron表达式,于是在执行完代码后一秒,任务又开始执行了

解决方法

程序执行时间太短没有关系,只要cron表达式秒的匹配符不设置为*就可以了。如图:

使用 @Scheduled 定时任务突然不执行了

在 SpringBoot 中可以通过 @Scheduled 注解来定义一个定时任务, 但是有时候你可能会发现有的定时任务到时间了却没有执行,但是又不是每次都不执行,这是怎么回事?

下面这段代码定义了一个每隔十秒钟执行一次的定时任务:

@Component
public class ScheduledTaskDemo {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskDemo.class);
    @Scheduled(cron = "0/10 * * * * *")
    public void execute() {
        logger.info("Scheduled task is running... ...");
    }
}

此时启动 SpringBoot 应用, 可以在控制台看到这个定时任务每隔10秒钟打印一条log

但是, 一切还没结束,如果没有相关log显示, 检查是否在入口类或者 Configuration 类上添加了@EnableScheduling 注解

在上面的相关代码中, 我们使用cron表达式来指定定时任务的执行时间点, 即从0秒开始, 每隔10秒钟执行一次, 现在我们再加一个定时任务:

@Component
public class SecondScheduledTaskDemo {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskDemo.class);
    @Scheduled(cron = "0/10 * * * * *")
    public void second() {
        logger.info("Second scheduled task is starting... ...");
        logger.info("Second scheduled task is ending... ...");
    }
}

现在再启动SpringBoot应用, 再看log:

注意log中定时任务执行的时间点, 第二个定时任务原本应该每隔10秒钟执行一次, 但是从23:12:20到23:13:55, 本该执行4次, 确只执行了2次.

难道是cron表达式不对?

No.

为了找到原因, 我们从 @Scheduled 注解的源码开始找:

*
 * <p>Processing of {@code @Scheduled} annotations is performed by
 * registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be
 * done manually or, more conveniently, through the {@code <task:annotation-driven/>}
 * element or @{@link EnableScheduling} annotation.
 *

划重点, 每一个有 @Scheduled 注解的方法都会被注册为一个ScheduledAnnotationBeanPostProcessor, 再接着往下看ScheduledAnnotationBeanPostProcessor:

/**
     * Set the {@link org.springframework.scheduling.TaskScheduler} that will invoke
     * the scheduled methods, or a {@link java.util.concurrent.ScheduledExecutorService}
     * to be wrapped as a TaskScheduler.
     * <p>If not specified, default scheduler resolution will apply: searching for a
     * unique {@link TaskScheduler} bean in the context, or for a {@link TaskScheduler}
     * bean named "taskScheduler" otherwise; the same lookup will also be performed for
     * a {@link ScheduledExecutorService} bean. If neither of the two is resolvable,
     * a local single-threaded default scheduler will be created within the registrar.
     * @see #DEFAULT_TASK_SCHEDULER_BEAN_NAME
     */
    public void setScheduler(Object scheduler) {
        this.scheduler = scheduler;
    }

重点来了, 注意这句话:

这句话意味着, 如果我们不主动配置我们需要的 TaskScheduler, SpringBoot 会默认使用一个单线程的scheduler来处理我们用 @Scheduled 注解实现的定时任务, 到此我们刚才的问题就可以理解了:

23:12:20, 第一个定时任务在线程pool-1-thread-1开始执行, 由于我们没有配置scheduler, 目前这个线程池pool-1里只有一个线程, 在打印了starting日志之后, 这个线程开始sleep;第二个定时任务也准备执行, 但是线程池已经没有多余线程了, 只能等待.

23:12:30, 第一个定时任务还在sleep, 第二个定时任务还在等待.

23:12:35, 第一个定时任务sleep结束, 打印ending日志并结束, 此时线程池空闲, 第二个定时任务从等待状态直接开始执行, 执行结束之后, 线程池空闲.

23:12:40, 线程池空闲, 第一个定时任务执行, 打印starting日志, 开始sleep.

搞清楚这个流程之后, 解决这个问题就很简单了.

根据刚才注释的描述, 我们只需要提供一个满足我们需要的 TaskScheduler 并注册到context中就可以了.

@Configuration
public class ScheduledTaskConfiguration implements SchedulingConfigurer {
    /**
     * Callback allowing a {@link TaskScheduler
     * TaskScheduler} and specific {@link Task Task}
     * instances to be registered against the given the {@link ScheduledTaskRegistrar}
     *
     * @param taskRegistrar the registrar to be configured.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(2);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }
}

上面的代码提供了一个线程池大小为2的taskScheduler, 现在再启动下SpringBoot看看效果.

可以看到, 当线程池里有两个线程的时候, 这两个定时任务各自按照预定的时间进行触发, 互不影响了.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法

    串行的定时任务 @Component public class ScheduledTimer { private Logger logger = Logger.getLogger(this.getClass()); /** * 定时任务,1分钟执行1次,更新潜在客户超时客户共享状态 */ @Scheduled(cron="0 0/1 8-20 * * ?") public void executeUpdateCuTask() { Thread current = Thread.curr

  • Springboot定时任务Scheduled重复执行操作

    今天用scheduled写定时任务的时候发现定时任务一秒重复执行一次,而我的cron表达式为 * 0/2 * * * * . 在源码调试的过程中,发现是我的定时任务执行过程太短导致的. 于是我另外写了个简单的定时任务 @Component public class TestJob { @Scheduled(cron = "* 0/2 * * * *") public void test() { System.out.println("测试开始"); System.o

  • Spring boot如何通过@Scheduled实现定时任务及多线程配置

    这篇文章主要介绍了Spring boot如何通过@Scheduled实现定时任务及多线程配置,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用@Scheduled 可以很容易实现定时任务 spring boot的版本 2.1.6.RELEASE package com.abc.demo.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spr

  • 基于Springboot执行多个定时任务并动态获取定时任务信息

    简介 因为一些业务的需要所有需要使用多个不同的定时任务,并且每个定时任务中的定时信息是通过数据库动态获取的.下面是我写的使用了Springboot+Mybatis写的多任务定时器. 主要实现了以下功能: 1.同时使用多个定时任务 2.动态获取定时任务的定时信息 说明 因为我们需要从数据库动态的获取定时任务的信息,所以我们需要集成 SchedulingConfigurer 然后重写 configureTasks 方法即可,调用不同的定时任务只需要通过service方法调用不用的实现返回对应的定时任

  • springboot定时任务@Scheduled执行多次的问题

    目录 springboot定时任务@Scheduled执行多次 原因 解决方法 使用 @Scheduled 定时任务突然不执行了 springboot定时任务@Scheduled执行多次 在spring boot开发定时任务时遇到一个很怪异的现象..我进行调试模式,在没有bug的情况下.执行了三 次才停止..如图: 原因 是因为执行时间太短,在CronSequenceGenerator.class的next方法. public Date next(Date date) { Calendar ca

  • springboot 定时任务@Scheduled实现解析

    这篇文章主要介绍了springboot 定时任务@Scheduled实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.pom.xml中导入必要的依赖: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version&g

  • Spring多定时任务@Scheduled执行阻塞问题解决

    目录 一. 问题描述 二. 场景复现 三. 解决方案 方案一:使用@Async注解实现异步任务 方案二:手动设置定时任务的线程池大小 四. 总结 一. 问题描述 最近项目中发现一个问题,计划每日凌晨4:40执行一个定时任务,使用注解方式: @Scheduled(cron = “0 40 4 * * ?”),cron表达式明显没有问题,但是这个定时任务总是不按时执行,有时候得等到8点多,有时候9点多才执行.后来查了下,原来这种定时方式默认是单线程执行的,恰好我这里有多个定时任务,并且其中有个在4:

  • SpringBoot执行定时任务@Scheduled的方法

    在做项目时,需要一个定时任务来接收数据存入数据库,后端再写一个接口来提供该该数据的最新的那一条. 数据保持最新:设计字段sign的值(0,1)来设定是否最新 定时任务插入数据:首先进行更新,将所有为1即新数据设置过期,然后插入新数据,设置sign为1.这两个操作是原子操作.通过添加事务来进行控制. Java 定时任务的几种实现方式 基于 java.util.Timer 定时器,实现类似闹钟的定时任务 使用 Quartz.elastic-job.xxl-job 等开源第三方定时任务框架,适合分布式

  • Springboot通过Scheduled实现定时任务代码

    定时任务一般会存在中大型企业级项目中,为了减少服务器.数据库的压力往往会采用时间段性的去完成某些业务逻辑.比较常见的就是金融服务系统推送回调,一般支付系统订单在没有收到成功的回调返回内容时会持续性的回调,这种回调一般都是定时任务来完成的.还有就是报表的生成,我们一般会在客户访问量过小的时候来完成这个操作,那往往都是在凌晨.这时我们也可以采用定时任务来完成逻辑.SpringBoot为我们内置了定时任务,我们只需要一个注解就可以开启定时为我们所用了. 在开发中,定时任务是常见的功能,在spring

  • springboot schedule 解决定时任务不执行的问题

    @schedule 注解 是springboot 常用的定时任务注解,使用起来简单方便,但是如果定时任务非常多,或者有的任务很耗时,会影响到其他定时任务的执行,因为schedule 默认是单线程的,一个任务在执行时,其他任务是不能执行的.解决办法是重新配置schedule,改为多线程执行.只需要增加下面的配置类就可以了. import org.springframework.boot.autoconfigure.batch.BatchProperties; import org.springfr

  • 深入剖析springBoot中的@Scheduled执行原理

    目录 springBoot @Scheduled执行原理 一.前言 二.@Scheduled使用方式 三.@Scheduled代码执行原理说明 @Scheduled 的一些坑 springBoot @Scheduled执行原理 一.前言 本文主要介绍Spring Boot中使用定时任务的执行原理. 二.@Scheduled使用方式 定时任务注解为@Scheduled.使用方式举例如下: //定义一个按时间执行的定时任务,在每天16:00执行一次. @Scheduled(cron = "0 0 1

  • 详解SpringBoot开发案例之整合定时任务(Scheduled)

    来来来小伙伴们,基于上篇的邮件服务,定时任务就不单独分项目了,天然整合进了邮件服务中. 不知道,大家在工作之中,经常会用到那些定时任务去执行特定的业务,这里列举一下我在工作中曾经使用到的几种实现. 任务介绍 Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务.Timer的优点在于简单易用:缺点是Timer的所有任务都是由同一个线程调度的,因此所有任务都是串行执行的.同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任

随机推荐