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

相关推荐
Sc Turing11 小时前
【Vue3-Bug】中路由加载页面直接显示空白
前端·bug
HvrI111 小时前
【Harmony_Bug】forEach + asyncawait 的异步陷阱
开发语言·华为·bug·harmonyos·鸿蒙
shanks6614 小时前
【Bug】 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
网络协议·bug·ssl
gxn_mmf1 天前
页面需要重加载才能显示的问题修改
前端·bug
YoungHong19921 天前
Git Bisect 使用指南:高效定位引入 Bug 的提交
git·bug
waves浪游2 天前
自动化测试实战篇
测试用例·bug·测试
DarkAthena3 天前
【ORACLE】记录一些ORACLE的merge into语句的BUG
数据库·oracle·bug
猫猫头有亿点炸3 天前
大数据可能出现的bug之flume
大数据·bug·flume
PLUS_WAVE3 天前
【CUDA 编译 bug】ld: cannot find -lcudart
服务器·c++·bug·环境·编译·cuda·ld
宁酱醇4 天前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug