简体   繁体   English

Spring - 计划任务 - 优雅关机

[英]Spring - Scheduled Task - Graceful Shutdown

I have a Spring-Boot application with a bean running a scheduled task at about 1 minute intervals, and this bean has a @PreDestroy method. 我有一个Spring-Boot应用程序,其中一个bean以大约1分钟的间隔运行一个计划任务,并且这个bean有一个@PreDestroy方法。

Is there a solution for allowing a task which is currently being executed to complete - or at least given some time to complete - before the life cycle reaches the pre-destroy phase? 是否存在允许当前正在执行的任务在生命周期达到预破坏阶段之前完成 - 或至少给予一些时间完成 - 的解决方案?

You need update configuration of ThreadPoolTaskScheduler . 您需要更新ThreadPoolTaskScheduler配置。 Set true for waitForJobsToCompleteOnShutdown (method setWaitForTasksToCompleteOnShutdown ). waitForJobsToCompleteOnShutdown设置为waitForJobsToCompleteOnShutdown (方法setWaitForTasksToCompleteOnShutdown )。

From documentation: 来自文档:

Set whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue. 设置是否等待计划任务在关闭时完成,不中断正在运行的任务并执行队列中的所有任务。 Default is "false", shutting down immediately through interrupting ongoing tasks and clearing the queue. 默认为“false”,通过中断正在进行的任务和清除队列立即关闭。 Switch this flag to "true" if you prefer fully completed tasks at the expense of a longer shutdown phase. 如果您希望以更长的关闭阶段为代价完全完成任务,请将此标志切换为“true”。

@Matej is right. @Matej是对的。 Some thing like this should do the trick 这样的事情应该可以解决问题

 @Bean
  public ThreadPoolTaskScheduler setSchedulerToWait(ThreadPoolTaskScheduler threadPoolTaskScheduler){
   threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
   return threadPoolTaskScheduler;
 }

Starting from Spring Boot 2.1.0, you can use this: 从Spring Boot 2.1.0开始,您可以使用:

@Bean
TaskSchedulerCustomizer taskSchedulerCustomizer() {
    return taskScheduler -> {
        taskScheduler.setAwaitTerminationSeconds(60);
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    };
}

TaskSchedulerCustomizer will be used to modify configured ThreadPoolTaskScheduler TaskSchedulerCustomizer将用于修改配置的ThreadPoolTaskScheduler

Details: 细节:

  1. ExecutorConfigurationSupport ExecutorConfigurationSupport
  2. TaskSchedulerCustomizer TaskSchedulerCustomizer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM