Springboot定时任务Scheduled重复执行

今天用scheduled写定时任务的时候发现定时任务一秒重复执行一次,而我的cron表达式为 * 0/2 * * * * 。

在源码调试的过程中,发现是我的定时任务执行过程太短导致的。

于是我另外写了个简单的定时任务

@Component
public class TestJob {
	@Scheduled(cron = "* 0/2 * * * *")
	public void test() {
		System.out.println("测试开始");
		System.out.println("测试结束");
	}
}

上述任务在启动之后一直执行。

然后我在任务后面加入线程睡眠1分钟。

@Component
public class TestJob {
	@Scheduled(cron = "* 0/2 * * * *")
	public void test() {
		System.out.println("测试开始");
		System.out.println("测试结束");
		try {
			Thread.sleep(60000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("睡眠结束");
	}
}

上述任务执行一次就没有再执行了。


所以我继续深入查看源码,发现问题在于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表达式秒的匹配符不设置为*就可以了。

    cron表达式可以设置为"0 0/2 * * * *",这样在执行到next方法中的doNext方法时就会发现时间增加1秒不符合cron表达式了,从而去寻找下一个合适的执行时间。


CronSequenceGenerator类参考:https://blog.csdn.net/ukulelepku/article/details/54310035

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值