Video in progress
The application runs as three instances and the @Scheduled job runs three times. How do you fix it?
@Scheduled runs independently in each JVM, and the instances don't know about each other. You need a distributed lock: ShedLock (a lock table in the database or Redis), a Quartz cluster, or running the job in one dedicated place (a Kubernetes CronJob).
📖 Answer
The most commonly used solution is ShedLock:
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
class SchedulingConfig {
@Bean
LockProvider lockProvider(DataSource ds) {
return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(ds))
.usingDbTime()
.build());
}
}
@Component
class InvoiceJobs {
@Scheduled(cron = "0 0 2 * * *", zone = "Asia/Tashkent")
@SchedulerLock(name = "dailyInvoices", lockAtMostFor = "30m", lockAtLeastFor = "1m")
void generateDaily() { /* ... */ }
}
Three instances wake up at the same time and try to update the row in the shedlock table. Only one succeeds, and the others skip the job.
Choosing the parameters correctly:
lockAtMostFor: how long until the lock is released if an instance dies. It should be longer than the job's longest run, otherwise a second instance starts in parallel.lockAtLeastFor: so the job doesn't run twice because of small clock differences between instances.
There are other things too:
- One thread by default. Spring Boot's scheduler pool is 1 thread (
spring.task.scheduling.pool.size). One hung job blocks the others too. - Idempotency. Even with the lock, the job shouldn't do any harm if it runs a second time (for example, a check like "is there already an invoice for today?").
- If you need a complex schedule, retries and history, Quartz (with a JDBC JobStore) or an external orchestrator is better.
Sign up to mark studied questions and save your progress.