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);

相关推荐
不念霉运11 小时前
为什么传统 Bug 追踪系统正在被抛弃?
软件测试·安全·gitee·开源·bug·devsecops
编程乐学(Arfan开发工程师)2 天前
56、原生组件注入-原生注解与Spring方式注入
java·前端·后端·spring·tensorflow·bug·lua
福大大架构师每日一题2 天前
pytorch v2.7.1 发布!全面修复关键BUG,性能与稳定性再升级,2025年深度学习利器必备!
pytorch·深度学习·bug
1nv1s1ble3 天前
记录rust滥用lazy_static导致的一个bug
算法·rust·bug
银色的白4 天前
开发记录:修复一些Bug,并实现两个功能
bug
吃货界的硬件攻城狮5 天前
【BUG】记STM32F030多通道ADC DMA读取乱序问题
stm32·嵌入式硬件·bug
星释5 天前
Yii2项目自动向GitLab上报Bug
前端·gitlab·bug·yii
upp6 天前
【bug】Error: /undefinedfilename in (/tmp/ocrmypdf.io.9xfn1e3b/origin.pdf)
ubuntu·pdf·bug·ghostscript
杨过姑父6 天前
部署开源版禅道,修改apache端口无效解决
bug·apache·软件工程·issue
chao_7897 天前
针对“仅某个地区出现Bug”的原因分析与解决方案
测试用例·bug