Spring boot 不断中断正在运行的 cronjob 任务,尽管它被配置为在关闭之前等待它们

问题描述 投票:0回答:1

在我的 sping 启动应用程序中,我有几个 Cron 作业应该能够在应用程序关闭之前完成运行。我正在使用

TaskSchedulerCustomizer
bean 来配置 spring 的默认任务调度程序以等待任务在关机时完成。

@Bean //https://stackoverflow.com/questions/43664259/spring-scheduled-task-graceful-shutdown
public TaskSchedulerCustomizer taskSchedulerCustomizer() { //Dit laat Spring het TaskScheduler object zelf aanmaken en customized het alleen.
    return taskScheduler -> {
        taskScheduler.setPoolSize(CORE_THREAD_POOL_SIZE);
        taskScheduler.setThreadNamePrefix("CronJob-");
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.setAwaitTerminationSeconds(AWAIT_TERMINATION_SECONDS);
    };
}

尽管将

setWaitForTasksToCompleteOnShutdown()
设置为
true
Spring 引导的正常关闭仍然会中断我正在运行的 cronjob 任务。我还在我的
application.properties
中添加了以下设置:

spring.task.scheduling.shutdown.await-termination=true
spring.task.scheduling.shutdown.await-termination-period=30s
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=30s

但这些也都被忽略了。在将

initialize()
设置为 true 之后,我还在
taskScheduler
上调用了
setWaitForTasksToCompleteOnShutdown()
以查看是否有帮助。但也没有帮助。

所以我几乎尝试了所有方法来让 spring 尊重我正在运行的 cronjob 任务。还有什么我可以尝试的吗?

这是我用于测试的 cronjob 代码

@Scheduled(cron = "* * * * * *")
public void schedule() throws InterruptedException {
    log.info("starting dummy scheduler");

    Thread.sleep(10000);
    log.info("ending dummy scheduler");
}
spring spring-boot scheduling spring-scheduled
1个回答
0
投票

我已经设法通过查看this SO question中的代码片段来解决问题。

当我创建自己的

TaskScheduler
bean,然后使用
configureTasks
实现的覆盖
SchedulingConfigurer
方法注册它时,一切正常。非常奇怪的是,它只能以这种方式工作,而不适用于
TaskSchedulerCustomizer
bean 或上述 application.properties 属性。继承人的代码:

@EnableScheduling 公共类 ContextSchedulingConfiguration 实现 SchedulingConfigurer {

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(securitytaskScheduler());
}

@Bean
public ThreadPoolTaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler taskScheduler= new ThreadPoolTaskScheduler();
    taskScheduler.setAwaitTerminationSeconds(120);
    taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    taskScheduler.setPoolSize(2);
    taskScheduler.setThreadNamePrefix("XXXXXXXXX");
    return taskScheduler;
}

}

这是来自this SO question

的粘贴
© www.soinside.com 2019 - 2024. All rights reserved.