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

相关推荐
永康李21 小时前
Pandas:从一个DataFrame中直接索引赋值到另一个索引位置出错的Bug及其解决方案
python·bug·pandas
NPE~21 小时前
Bug:Goland debug失效详细解决步骤【合集】
go·bug·goland·dlv失效
Urf_read1 天前
改BUG:远程连接redis失败,可能是防火墙的问题
java·redis·python·bug
Tlog嵌入式3 天前
单片机常见bug记录(长期更新)
单片机·嵌入式硬件·bug
会发光的猪。4 天前
el-input无法输入0.0001的小数,自动转换为0在vue3中的bug
前端·javascript·vue.js·elementui·bug
shandianchengzi4 天前
【BUG】LLM|Ubuntu 用 ollama 部署 DeepSeek 但没输出,llama 有输出
ubuntu·llm·bug·llama·ollama·deepseek
抽象具象化5 天前
Bug日记:Linux中systemctl restart network失败问题,网络故障
linux·运维·bug
王天华帅哥5 天前
day3 改bug
bug
吉凶以情迁5 天前
lua的local 变量和self 变量的理解理解后解决自己写的bug.
开发语言·bug·lua
qq_527887875 天前
【已解决】TypeError: AsyncConnectionPool.__init__(), new install bug, httpx==0.24.1
bug·httpx