Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
Relay's SLA sweep runs every fifth second. On one instance it escalates two overdue tickets; on two instances it escalates them twice. ShedLock keeps one lock row in PostgreSQL so each tick runs once, by a, a, then b, never two at once.
What you will learn
- Turn on scheduling and pick between fixedRate, fixedDelay and cron
- Explain why two instances of an app run every scheduled job twice
- Add a ShedLock JDBC lock row so only one instance runs each tick
- Set lockAtLeastFor and lockAtMostFor and know what each protects against
Before you start
- Connect Spring Boot to PostgreSQL
- Spring Boot basics
Relay has an SLA sweep: every few seconds, find tickets that have been OPEN for more than four hours and escalate them. One method on a timer does it. Then we run the app twice, like production does, and every ticket gets escalated twice. ShedLock fixes that with one lock row in the database.
One annotation turns scheduling on
Put @EnableScheduling on the main application class. Without it, every @Scheduled method is simply ignored, with no error. (The project also starts a small clock so every log line begins with t+ and the seconds since start.)
fixedRate, fixedDelay and cron
@Component
@Profile("timers")
public class TimerDemo {
private static final Logger log =
LoggerFactory.getLogger(TimerDemo.class);
@Scheduled(fixedRate = 2000)
public void everyTwoSeconds() throws InterruptedException {
log.info("{} fixedRate starts", Stamp.t());
Thread.sleep(1500);
}
@Scheduled(fixedDelay = 2000)
public void twoSecondsAfterTheLastEnd() throws InterruptedException {
log.info("{} fixedDelay starts", Stamp.t());
Thread.sleep(1500);
}
@Scheduled(cron = "*/5 * * * * *")
public void everyFifthSecond() {
log.info("{} cron starts", Stamp.t());
}
}
fixedRate = 2000 (milliseconds) starts a new run every two seconds counted from the last start; in the log that's 5.1, 7.1, 9.1. The job takes 1.5 s, so it's done before the next one is due. fixedDelay = 2000 starts the two seconds when the last run ends: 1.5 + 2, so a run every 3.5 seconds. cron doesn't care about the job at all; the clock decides, every fifth second, here at 7.8, 12.8 and 17.8.
Two instances, one job, run twice
In production you usually run the same app more than once. Without a lock, instance a sweeps at every tick and escalates two tickets, and instance b does exactly the same at exactly the same ticks. Each overdue ticket is escalated twice. Add a third instance and it's three times. Each instance has its own scheduler, and nothing tells them the other one exists.
ShedLock: four dependencies
spring-boot-starter-jdbc (the data source and JdbcClient), the PostgreSQL driver (both instances share one database), shedlock-spring (the annotations) and shedlock-provider-jdbc-template (locks as rows in a table). Both ShedLock libraries share one version, set once in a shedlock.version property (7.11.0 here).
Where the lock lives
@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
@ConditionalOnProperty(name = "shedlock.enabled",
havingValue = "true", matchIfMissing = true)
public class LockConfig {
@Bean
LockProvider lockProvider(DataSource dataSource,
@Value("${instance.name}") String instance) {
var config = JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(dataSource))
.withLockedByValue(instance)
.usingDbTime()
.build();
return new JdbcTemplateLockProvider(config);
}
}
@EnableSchedulerLock turns locking on, with a default release after 30 seconds at the latest. withJdbcTemplate makes the lock a row in the shedlock table that every instance reads and writes. withLockedByValue writes the instance name into locked_by, so you can see who holds it. usingDbTime() lets the database clock decide, so instances with different clocks still agree. (The @ConditionalOnProperty is only there so the demo can switch ShedLock off with shedlock.enabled=false.)
One job, one lock
@Scheduled(cron = "*/5 * * * * *")
@SchedulerLock(name = "slaSweep",
lockAtMostFor = "PT30S", lockAtLeastFor = "PT4S")
public void sweep() {
List<Ticket> overdue = jdbc
.sql("select id, title, hours_open from ticket"
+ " where status = 'OPEN' and hours_open > 4")
.query(Ticket.class).list();
for (Ticket t : overdue) {
log.info("{} [{}] escalated #{} {}",
Stamp.t(), instance, t.id(), t.title());
}
log.info("{} [{}] sweep done, {} escalated",
Stamp.t(), instance, overdue.size());
}
Both instances fire on the same second. @SchedulerLock(name = "slaSweep") means: before running, take the row called slaSweep; if it's already taken, don't run at all.
With two instances running, three ticks went like this. At 7.9 s both went for the row; a got it (locked_by = a) and escalated two tickets, while b logged Not executing 'slaSweep'. It's locked. At 12.9 s, the same. At 17.9 s it was b's turn, and a skipped. Three ticks, three runs, by a, a and b, never two at once. The database decides who wins each tick.
How long the lock is held
| Setting | Here | Protects against |
|---|---|---|
lockAtLeastFor | 4 s | a quick job finishing, releasing the row, and the other instance (with a slightly late clock) running the same tick again |
lockAtMostFor | 30 s | an instance that dies mid-run and would otherwise block the job forever |
The sweep is quick, but the row stays locked for 4 s, and the next tick comes 5 s later when it's free again. In the table after a run, lock_until minus locked_at is 4 seconds. Keep lockAtLeastFor below the interval, and lockAtMostFor above the longest real run.
Common mistakes
- No
@EnableScheduling. Nothing runs, and nothing complains. - fixedRate for a job that can outlast its rate. Runs start to pile up behind each other. Use fixedDelay.
- Scaling out without a lock. Every instance runs every job.
lockAtMostForshorter than a real run. The lock expires while the job is still working, and another instance starts it again.
Try it yourself
Start both instances with shedlock.enabled=false and count the "escalated" lines for one tick. Then turn it back on and count again. What does the locked_by column show between ticks?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
