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 小时前
Qt自定义控件bug记录
bug
l1t1 天前
duckdb数据库CROSS JOIN LATERAL 中使用 EXISTS子查询的一个bug
数据库·bug
Zsh-cs1 天前
苍穹外卖day11销量TOP10商品展示,前端有商品名字但无销量(已解决)
bug
数字芯片实验室2 天前
仿真器出bug了?分频时钟竞争的诡异仿真现象
fpga开发·bug
Zsh-cs2 天前
苍穹外卖day9前端订单分页查询后订单菜品不展示(已解决)
bug
北数云3 天前
北数云内测|AI 需求发布区 + Bug/建议长期征
bug·模型·智能体
天上掉下个牛霸天4 天前
Bug悬案:技术侦探如何破案
bug
f***24114 天前
Bug悬案:程序员破案指南
bug
e***98574 天前
Bug破案现场:技术团队的悬疑推理秀
bug
数字芯片实验室4 天前
边界值测试:一个”==”引发的芯片bug
fpga开发·bug