Spring - Scheduled Task - Graceful Shutdown

我的未来我决定 提交于 2020-05-29 03:12:24

问题


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.

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?


回答1:


You need update configuration of ThreadPoolTaskScheduler. Set true for waitForJobsToCompleteOnShutdown (method 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. Switch this flag to "true" if you prefer fully completed tasks at the expense of a longer shutdown phase.




回答2:


Starting from Spring Boot 2.1.0, you can use this:

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

TaskSchedulerCustomizer will be used to modify configured ThreadPoolTaskScheduler

Details:

  1. ExecutorConfigurationSupport
  2. TaskSchedulerCustomizer



回答3:


@Matej is right. Some thing like this should do the trick

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


来源:https://stackoverflow.com/questions/43664259/spring-scheduled-task-graceful-shutdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!