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, as covered in the earlier chapters.
What happens by default
When the application receives SIGTERM, Spring closes the application context and stops the scheduler. By default the scheduler does not wait. It stops starting new runs and interrupts the threads that are running a task. A task halfway through a batch can be cut off, leaving partial work behind.
You can avoid this by telling the scheduler to wait for running tasks. It still starts no new runs.
Waiting for running tasks
Spring Boot exposes two properties for the auto-configured scheduler:
spring:
task:
scheduling:
shutdown:
await-termination: true
await-termination-period: 30sawait-termination makes shutdown block until running tasks finish. await-termination-period caps that wait. If a task is still running when the period ends, the scheduler interrupts it and shutdown continues.
Writing tasks that survive interruption
A wait period is only a limit. A long task must also respond to the interrupt when it arrives. Check the interrupt flag between units of work so the task can stop at a safe point:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class BatchJob {
private static final Logger log = LoggerFactory.getLogger(BatchJob.class);
@Scheduled(fixedDelay = 60000)
public void processBatch() {
List<Integer> items = List.of(1, 2, 3, 4, 5);
for (Integer item : items) {
if (Thread.currentThread().isInterrupted()) {
log.warn("Interrupted before item {}, stopping early", item);
return;
}
process(item);
}
}
private void process(Integer item) {
log.info("processed {}", item);
}
}Process each item so that a restart can safely resume. Mark items as done as you go instead of at the end of the batch. Then an early stop loses at most one item of work.
The @Async executor is separate
A @Scheduled method that is also @Async hands its work to another executor. The scheduler's wait setting does not cover that work. The task executor has its own matching properties:
spring:
task:
execution:
shutdown:
await-termination: true
await-termination-period: 30sSet both if you use both.
Match the platform's timeout
The wait only helps if the process is allowed to live that long. Check these limits:
- Kubernetes:
terminationGracePeriodSecondsdefaults to 30 seconds. After that the container receives SIGKILL, which no Java code can handle. Set it above your await period. - Docker:
docker stopwaits 10 seconds by default before SIGKILL. - Web requests:
server.shutdown=gracefulcovers in-flight HTTP requests, not scheduled tasks. Phases are bounded byspring.lifecycle.timeout-per-shutdown-phase, which defaults to 30 seconds.
Common mistakes
| Mistake | Effect |
|---|---|
| Not setting `await-termination` | Running tasks are interrupted immediately on deploy |
| Wait period longer than the platform's kill timeout | The process is killed before the wait ends |
| Catching `InterruptedException` and ignoring it | The task keeps running until the period expires |
| Configuring only the scheduler when using `@Async` | Async work is cut off at shutdown |
Exercise
A scheduled task usually takes 45 seconds. You set spring.task.scheduling.shutdown.await-termination-period to 60s, but deployments on Kubernetes still show the task being killed midway. What is the likely cause, and what do you change?
Show answer
The pod's terminationGracePeriodSeconds is probably still the default 30 seconds, so Kubernetes sends SIGKILL before the 60-second wait ends. Raise terminationGracePeriodSeconds above 60 (for example 75). Also confirm that await-termination is set to true, because the period has no effect without it.