Spring 使用调度程序启动关机

Spring Boot Shutdown with Scheduler

我正在使用 Spring Boot + Spring Task Scheduler 来创建轮询应用程序。我计划在维护期间使用执行器关闭应用程序 windows(请参阅执行器的关闭端点:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-endpoints)。

我的问题是,Spring 是否足够聪明地在正常关闭应用程序之前完成正在进行的任务?如果正在进行的任务在关机前完成,Spring 是否足够聪明不启动另一个任务?

谢谢。

您可以通过设置

来控制它
ThreadPoolTaskExecutor#waitForTasksToCompleteOnShutdown

为真。

继承setter的javadoc中有很好的解释

org.springframework.scheduling.concurrent.ExecutorConfigurationSupport#setWaitForTasksToCompleteOnShutdown

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...

spring 调度程序默认使用

java.util.concurrent.ThreadPoolExecutor

的 javadoc 中所述,在关机期间不会启动新任务
java.util.concurrent.ThreadPoolExecutor#shutdown

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted...

自spring boot 2.1 开始你可以设置如下属性

# Whether to wait for running jobs to complete on shutdown.
spring.quartz.wait-for-jobs-to-complete-on-shutdown=false