Sub topic 3
Scheduled Tasks in Spring Boot
Assume you know basic Spring beans, configuration properties, and thread behavior. This chapter focuses on operating scheduled tasks safely rather than declaring their basic triggers.
Testing scheduled tasks
Test the job’s business logic separately from its timer. Put the work in a service method that accepts inputs and returns a result. Then test that method directly. A timer test should only verify that the task is registered and eventually invokes the service.
In a Spring integration test, use a short test-only delay and wait with a bounded timeout. Do not use an unbounded sleep. Disable scheduling when testing unrelated application components with spring.task.scheduling.enabled=false, if your Spring Boot version supports that property.
Shutting down cleanly
A scheduler can stop accepting new executions while existing executions finish. Configure a termination wait period:
spring:
task:
scheduling:
shutdown:
await-termination: true
await-termination-period: 30sTasks should also respond to interruption. Avoid swallowing InterruptedException; restore the interrupt flag or stop the operation.
Registering tasks in code
Use SchedulingConfigurer when schedules come from a database, feature flag, or other runtime decision. Annotation-based scheduling is simpler for fixed application configuration.
@Configuration
class JobConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
registrar.addCronTask(
() -> System.out.println("registered in code"),
"0 */5 * * * *"
);
}
}Scheduled tasks across multiple instances
Each application instance normally owns its own scheduler. With three instances, a task may run three times. This can create duplicate emails, exports, or payments.
Choose an explicit policy:
| Requirement | Common solution |
|---|---|
| Every instance may run it | Make the operation idempotent |
| Only one instance may run it | Use a database lock, such as ShedLock |
| Durable jobs and clustering | Use Quartz |
Scheduling with virtual threads
Virtual threads can make many blocking tasks cheaper to wait on, but they do not provide distributed locking or unlimited database capacity. A virtual-thread scheduler still needs bounded downstream resources, such as connection pools. Test the chosen executor and monitor task duration before switching.
When to use Quartz
Use Spring’s scheduler for lightweight, in-process timers. Choose Quartz when you need persistent job definitions, misfire handling, calendars, retries, or clustered coordination. Quartz adds configuration and operational overhead, so it is usually unnecessary for a single instance with simple recurring work.
Exercise
Why can a scheduled task run three times after deploying three application instances?
Show answer
Each instance has its own scheduler. Use idempotency or a shared coordination mechanism when only one execution is allowed.