Sub topic 10
Shutting down cleanly
This chapter assumes you can already declare @Scheduled methods and know that Spring Boot runs them on a scheduler thread pool. It covers what happens to a task that is running when the application stops, and how to configure the scheduler so that the task finishes or stops safely.
What happens at shutdown by default
When the application context closes, Spring destroys the scheduler bean. Context closing is triggered by SIGTERM, by a call to SpringApplication.exit, or by the end of a test. The shutdown has two effects:
- Spring cancels all future runs of every scheduled task. A
fixedRateor cron task will not fire again. - Spring stops the thread pool. Unless you configure otherwise, it does not wait for tasks that are already running. It interrupts them and lets the JVM continue to exit.
An interrupt is a request, not a kill. The thread's interrupted flag is set. Blocking calls such as Thread.sleep, Future.get or many I/O operations throw InterruptedException or return early. Code that never checks the flag keeps running until the JVM exits, and then it is cut off abruptly.
For a task that only logs a line, none of this matters. It matters when a task:
- writes several rows that must be consistent,
- calls an external system that has no undo,
- sends a batch of messages and records progress afterwards.
A task like that can be stopped halfway through, and nothing in the logs says so.
Waiting for running tasks
Spring Boot exposes two properties for the auto-configured scheduler.
spring:
task:
scheduling:
pool:
size: 4
shutdown:
await-termination: true
await-termination-period: 30sWith await-termination: true, the scheduler stops accepting new runs and waits for the running ones to finish. It waits at most await-termination-period. If tasks are still running after that time, the pool is forced to stop and the remaining tasks are interrupted.
Both properties are needed. Without await-termination-period, Spring waits for no time at all, which behaves like the default. Choose the period from the longest task you can tolerate waiting for, not from the average run time.
flowchart TDThe diagram below shows the sequence.
Defining your own scheduler
If you declare your own TaskScheduler bean, Spring Boot's auto-configured one backs off, and the spring.task.scheduling.* properties no longer apply to your bean. Set the same behavior in code:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class SchedulerConfig {
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(4);
scheduler.setThreadNamePrefix("sched-");
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationSeconds(30);
return scheduler;
}
}setWaitForTasksToCompleteOnShutdown(true) is the code equivalent of await-termination: true. setAwaitTerminationSeconds(30) is the equivalent of the period.
Tasks that run on another executor
A task marked with @Async is only handed off by the scheduler thread. The real work runs on the async executor, which is a different pool with its own shutdown settings. Waiting on the scheduler does not wait for that work.
Boot's auto-configured async executor has its own properties:
spring:
task:
execution:
shutdown:
await-termination: true
await-termination-period: 30sSet both pools if you use both. A common mistake is to configure only the scheduler, deploy, and still see @Async work cut off.
Writing tasks that cooperate
A shutdown period only helps if the task can finish or stop within it. For a long task, check the interrupt flag between units of work, and stop at a point where your data is consistent.
import java.util.List;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ExportJob {
private static final Logger log = LoggerFactory.getLogger(ExportJob.class);
@Scheduled(fixedDelay = 60000)
public void export() {
List<Integer> batches = IntStream.range(0, 100).boxed().toList();
for (Integer batch : batches) {
if (Thread.currentThread().isInterrupted()) {
log.warn("Shutdown requested, stopping before batch {}", batch);
return;
}
processBatch(batch);
}
log.info("Export finished");
}
private void processBatch(int batch) {
try {
Thread.sleep(200); // stands in for real work
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag
log.warn("Interrupted during batch {}", batch);
}
}
}The design points are:
- Restore the flag. If you catch
InterruptedException, callThread.currentThread().interrupt()again. Otherwise the loop inexportcannot see that shutdown was requested and keeps going. - Stop between batches, not inside one. Each batch is a unit that is either complete or not started.
- Make the work resumable. Even a cooperative task can be killed if the period expires, or if the process dies from a crash or
SIGKILL. Record progress, or make each batch idempotent, so the next run can continue safely.
Matching the platform's timeout
The scheduler's wait is only one limit among several. The platform that runs your application also has a deadline after which it kills the process.
| Layer | Setting | Effect |
|---|---|---|
| Scheduler | `spring.task.scheduling.shutdown.await-termination-period` | Maximum wait for scheduled tasks |
| Async executor | `spring.task.execution.shutdown.await-termination-period` | Maximum wait for `@Async` work |
| Web server | `server.shutdown=graceful` and `spring.lifecycle.timeout-per-shutdown-phase` | Wait for in-flight HTTP requests |
| Kubernetes | `terminationGracePeriodSeconds` (default 30) | Time before `SIGKILL` |
| Docker | `docker stop --time` (default 10) | Time before `SIGKILL` |
If the platform kills the process after 10 seconds, a 30-second scheduler period never gets to apply. Set the platform timeout to be longer than the sum of the waits that can happen in sequence, with some margin. For Kubernetes, also remember that the pod can keep receiving traffic for a short time after SIGTERM is sent.
Keep the process receiving the signal in mind too. If your container starts the application through a shell script that does not forward signals, the JVM never sees SIGTERM. In that case no Spring setting can help, and the shutdown hooks do not run.
Verifying the behavior
You can check your configuration without deploying. Start the application with a task that sleeps for 20 seconds, then send it SIGTERM with kill <pid> or Ctrl+C in a terminal. Watch the log:
- With
await-terminationoff, you should see the process exit within a second or two, and the task's final log line does not appear. - With it on and a 30-second period, the process stays alive until the task logs its last line, then exits.
- With it on and a 5-second period, the process exits after about 5 seconds, and the task's interrupt handling appears in the log.
Log a line at the start and end of every long task. Those lines are the only evidence of whether a shutdown cut a run short.
Common errors
- Setting only
await-termination: true. Without a period, the wait is zero. Always set both. - Configuring the scheduler but not the async executor.
@Asyncwork is on a separate pool. - Defining a custom
TaskSchedulerand keeping the YAML. The properties no longer apply to your bean. - A period longer than the platform's kill timeout. The process is killed before the wait ends.
- Treating the wait as a guarantee. It is a bounded courtesy. Design tasks so that a forced stop is recoverable.
Exercise
A service runs a nightly job that takes about 40 seconds. You set spring.task.scheduling.shutdown.await-termination to true and leave the period unset. The job also calls an @Async method that does the final upload. On deployment the pod is stopped at 02:00:10 and the upload is sometimes missing. Name three separate problems that could cause this, and the setting that fixes each.
Show answer
First, with no await-termination-period the scheduler does not wait, so the running job is interrupted; set await-termination-period to more than 40s, such as 60s. Second, the @Async upload runs on the async executor, which is a separate pool; set spring.task.execution.shutdown.await-termination to true and give it a period. Third, the platform can kill the process before either wait ends (for example Kubernetes terminationGracePeriodSeconds defaults to 30s); raise it above the combined waits. Making the job check the interrupt flag and be resumable or idempotent covers the case where a forced stop still happens.