Bug:ThreadPoolTaskScheduler搭配CronTask完成定时任务,关闭scheduler后CronTask任务仍然执行?

【问题】执行下面代码后,关闭ThreadPoolTaskScheduler,CronTask仍然继续执行。

复制代码
@Configuration
public class config {
    @Bean
    public String getString() throws InterruptedException {
        Runnable runnable = () -> {
            try {
                System.out.println("hello runnable");
                Thread.sleep(2000);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        };
        CronTask cronTask = new CronTask(() -> {
            try {
                System.out.println("hello cronTask");
                Thread.sleep(2000);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }, "* * * * * ?");

        ThreadPoolTaskScheduler testScheduler = new ThreadPoolTaskScheduler();
        testScheduler.setPoolSize(2);
        testScheduler.initialize();
        testScheduler.scheduleWithFixedDelay(runnable, 10);
        testScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        Thread.sleep(6000);
        testScheduler.setAwaitTerminationMillis(100);
        testScheduler.setWaitForTasksToCompleteOnShutdown(true);
        testScheduler.shutdown();
        System.out.println("shutdown");
        return new String("123");
    }
}
=================================================
hello runnable
hello cronTask
hello runnable
hello cronTask
hello runnable
shutdown
hello cronTask

schedule(CronTask task):使用 CronTask 允许你基于 Cron 表达式定义复杂的调度规则。任务将在指定的时间点按 Cron 表达式执行,例如每天的特定时间或每小时。
scheduleWithFixedDelay(Runnable task, long delay):这个方法基于固定的延迟时间调度任务。任务在上一次执行完成后,等待指定的延迟时间,然后再次执行。适合需要间隔性执行的任务,不关心具体的执行时间。


【解决办法】

复制代码
setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean executeExistingDelayedTasks)
  • 如果设置为 true,在调用 shutdown 方法后,已经排定但尚未执行的延迟任务仍然会被执行。

  • 如果设置为 false,则在 shutdown 后,所有已排定的延迟任务将不会被执行。

    testScheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

相关推荐
初圣魔门首席弟子1 天前
c++ bug 记录(merge函数调用时错误地传入了vector对象而非迭代器。)
java·c++·bug
Qiuner1 天前
历劫波,明真我——Debug Commune
ai·开源·bug·debug·信息差·信息·交流
川石课堂软件测试3 天前
什么是BUG,你对BUG的了解有多少?
android·linux·服务器·python·功能测试·bug·安全性测试
仰望星空的凡人3 天前
【BUG排查】基于RH850F1KMS1的主控出现系统中断错误,调试FEIC的值为0x11
单片机·bug·rh850·renesas
Vanranrr3 天前
Git Commit Message 最佳实践:从一次指针Bug说起
git·bug
初圣魔门首席弟子4 天前
c++ bug 函数定义和声明不一致导致出bug
开发语言·c++·bug
xuyuan19984 天前
修复1个Bug,引爆3个新Bug?回归测试的智慧
功能测试·测试用例·bug
三十_A4 天前
【实录】使用 patch-package 修复第三方 npm 包中的 Bug
前端·npm·bug
BrightMZM4 天前
记录一下Unity的BUG,Trial Version
unity·bug·打包·trial
一只自律的鸡5 天前
【bug日记】python找不到包
bug