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

相关推荐
Pan Zonghui13 小时前
GitHub Bug反馈与修复全流程指南
github·bug
初圣魔门首席弟子1 天前
bug 2026.05.15(以前能运行的java springboot项目突然间不能运行后台数据了)
java·开发语言·bug
Desenberg2 天前
【Claude Code】因为中途修改配置路径导致Claude Code 插件安装失败
windows·bug
QuestLab2 天前
维护 Hermes Agent CN 过程中的碎碎念,以及从bug上得到的一点点启发
bug
java修仙传3 天前
Java 实习日记:一次 Excel 导入校验 Bug 的定位与数据更新逻辑优化
java·数据库·bug·excel·后端开发
当战神遇到编程3 天前
软件测试基础入门:从 BUG 到测试用例设计完整指南
测试用例·bug
Bear on Toilet5 天前
3. BUG篇
bug
编程探索者小陈5 天前
【测试】之BUG篇
bug
棋宣6 天前
uni-app编译到微信小程序中,父传子props首次传递数据不接收的bug
微信小程序·uni-app·bug
wqdian_com6 天前
华为手机浏览器的一个bug
服务器·华为·bug