Sub topic 12
Scheduled tasks across multiple instances
This chapter assumes you can declare @Scheduled methods, understand the scheduler thread pool, and have a relational database in your application.
The duplicate-execution problem
@Scheduled is local to one JVM. Each Spring Boot process runs its own scheduler and knows nothing about other processes. If you deploy three replicas, a nightly report with cron = "0 0 2 * * *" runs three times at 02:00. The same applies to rolling deployments, where old and new versions briefly overlap.
For idempotent work, such as refreshing a cache, this wastes resources. For non-idempotent work, such as sending invoices or emails, it causes real damage.
Options
| Approach | How it works | Trade-off |
|---|---|---|
| Single scheduler instance | Enable scheduling only on one instance, for example with a profile or property. | Simple, but a single point of failure with no automatic failover. |
| Lock library such as ShedLock | Each run tries to take a named lock in a shared store. | Small change. It guarantees at most one concurrent run, not exactly one run. |
| Quartz with JDBC clustering | The scheduler itself coordinates through database tables. | Most capable, with more setup. Chapter on Quartz covers it. |
| External trigger | A Kubernetes CronJob or cloud scheduler calls an endpoint or starts a job. | Clean separation, but it adds infrastructure. |
Gating scheduling with a property
The simplest fix uses a conditional property. Put @EnableScheduling on a configuration class and switch it on for one instance:
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ConditionalOnProperty(name = "app.scheduling.enabled", havingValue = "true")
public class SchedulingSwitch {
}Set app.scheduling.enabled=true on exactly one deployment. If that instance dies, nothing runs until you intervene.
Locking with ShedLock
ShedLock is a library, not part of Spring. Add shedlock-spring and shedlock-provider-jdbc-template, then create the lock table:
CREATE TABLE shedlock (
name VARCHAR(64) NOT NULL PRIMARY KEY,
lock_until TIMESTAMP(3) NOT NULL,
locked_at TIMESTAMP(3) NOT NULL,
locked_by VARCHAR(255) NOT NULL
);Register a lock provider:
import javax.sql.DataSource;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT10M")
public class LockConfig {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(
JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(dataSource))
.usingDbTime()
.build());
}
}Then annotate each task:
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class NightlyReportJob {
@Scheduled(cron = "0 0 2 * * *", zone = "Europe/Berlin")
@SchedulerLock(name = "nightlyReport",
lockAtMostFor = "PT30M",
lockAtLeastFor = "PT1M")
public void run() {
// generate the report once per night
}
}The two durations matter:
lockAtMostForis a safety limit. If the instance holding the lock crashes, the lock expires after this time. Set it longer than the task's worst-case runtime. If it is shorter, another instance can start while the first is still working.lockAtLeastForkeeps the lock after a fast run finishes. This stops an instance with a slightly fast clock from running the task again right after the first one.
usingDbTime() makes the database supply timestamps, so clock drift between instances does not affect locking.
Common mistakes
- Treating the lock as exactly-once. A lock prevents concurrent runs. A task can still fail midway and be retried, so keep the work idempotent where you can.
- Reusing lock names. Two different tasks with the same
nameblock each other. - Setting
lockAtMostFortoo short. Long runs then overlap with the next holder. - Relying on a single-instance flag during rolling deployments. Old and new pods can both have it set.
Exercise
Your app runs on four instances. A task with @Scheduled(fixedRate = 60000) and @SchedulerLock(name = "sync", lockAtMostFor = "PT10S") sometimes runs on two instances at once, and each run takes about 30 seconds. What is wrong, and how do you fix it?
Show answer
lockAtMostFor is 10 seconds, but the task needs about 30. The lock expires while the first run is still working, so another instance acquires it and starts a second run. Set lockAtMostFor above the worst-case runtime, for example PT5M, and consider a lockAtLeastFor to stop immediate re-runs from instances with clock differences.