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

相关推荐
初圣魔门首席弟子2 天前
bug【已解决】腾讯 WorkBuddy 无法访问:校园网限制导致的网络问题排查全记录
bug
乐兮创想 小林4 天前
企业官网的运维分工模型:内容自助、Bug 终身免费修与服务器托管的边界设计
运维·服务器·bug·网站建设·企业官网·北京网站建设公司
菠萝猫yena4 天前
bug描述规范
bug
乐兮创想 小林4 天前
生物科技官网的工程化设计:产品×应用二维信息架构、多语言与国际化 SEO 实践
运维·服务器·bug·网站建设·企业官网·北京网站建设公司
调问开源问卷DWSurvey4 天前
调问更新5.16~5.30:解锁Excel图片上传,修复多项高频体验Bug
bug
胡图图不糊涂^_^4 天前
测试BUG篇
学习·bug·测试
搬石头的马农4 天前
从零配置Claude自动修Bug:6步打造全自动开发流程
java·人工智能·python·bug·ai编程
winlife_5 天前
让 AI 自动跑 PlayMode 回归测试:从 BUG 注入到自动判 FAIL 的完整闭环
人工智能·unity·bug·ai编程·mcp·回归测试·游戏测试
坚果的博客5 天前
Flutter OHOS SDK 版本目录校验 Bug 修复实战
flutter·bug
加强洁西卡5 天前
【Bug】解决vscode里ssh连接的虚拟机的codex的侧边栏打开只有logo没有登录或输入框的问题
bug