Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Show how to make a @Scheduled method run on only one instance in a cluster using ShedLock with a JDBC lock provider, and explain lockAtMostFor and lockAtLeastFor.

We add ShedLock's Spring and JDBC provider modules, create the shedlock table, enable it with @EnableSchedulerLock(defaultLockAtMostFor = "PT10M") and a JdbcTemplateLockProvider bean, and put @SchedulerLock(name = "reminders", lockAtMostFor = "PT10M", lockAtLeastFor = "PT1M") next to @Scheduled. lockAtMostFor is a safety release in case the node holding the lock dies, so it must be well above the normal run time, and lockAtLeastFor keeps the lock for a minimum time so another node whose clock is slightly behind does not run the same execution again. Nodes that do not get the lock simply skip that run.

Why this question is asked

ShedLock is the most common way to stop a @Scheduled job running on every instance of a Spring service, and it is popular because it is small: one table, two annotations. But the two lock durations are easy to get wrong, and getting them wrong produces exactly the duplicate or missed runs we were trying to prevent. Interviewers ask for the code and the two settings to see whether we know how the lock actually works. In this answer, we will set up ShedLock with a JDBC provider, annotate the job, follow what happens on two nodes at the scheduled time, and then look closely at lockAtMostFor and lockAtLeastFor, including what happens when a run lasts longer than the lock.

1A Quick Recap of What ShedLock Does

Every instance of a scaled-out service runs its own scheduler, so a @Scheduled method fires on all of them at the same moment. ShedLock adds a check in front of the method: before running, the instance tries to take a named lock stored in a shared place, here a database table. If it gets the lock, it runs the method and releases the lock at the end. If another instance already holds it, this instance skips the execution entirely.

Notice that ShedLock is not a scheduler and not a queue. It does not decide when jobs run, that is still @Scheduled, and it does not remember skipped executions to run them later. It only answers one question at each firing: is someone else already doing this?

2Setting Up the Table and the Lock Provider

We need the shedlock-spring module and the provider for JdbcTemplate, plus a table. The table has one row per lock name, holding when the lock expires, when it was taken and by whom.

XML
<!-- pom.xml: check the current ShedLock version -->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jdbc-template</artifactId>
</dependency>
-- Flyway or Liquibase migration
CREATE TABLE shedlock (
name VARCHAR(64) NOT NULL PRIMARY KEY,
lock_until TIMESTAMP NOT NULL,
locked_at TIMESTAMP NOT NULL,
locked_by VARCHAR(255) NOT NULL
);
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT10M")
class SchedulingConfig {
@Bean
LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(
JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(dataSource))
.usingDbTime() // compare times using the database clock, not each node's clock
.build());
}
}

The durations are ISO-8601 strings: PT10M is ten minutes, PT30S thirty seconds. defaultLockAtMostFor applies to any @SchedulerLock that does not set its own value. usingDbTime() makes ShedLock use the database's current time in its SQL instead of the time on each application node, which removes one whole class of clock problems; it is supported for common databases, so check your provider version.

3Annotating the Job

The job keeps its normal @Scheduled annotation and gains @SchedulerLock. The name identifies the lock row, so every instance must use the same name for the same job, and different jobs must use different names.

Java
@Component
class ReminderJob {
@Scheduled(cron = "0 0 8 * * *", zone = "Europe/London")
@SchedulerLock(name = "reminders", lockAtMostFor = "PT10M", lockAtLeastFor = "PT1M")
public void sendReminders() {
LockAssert.assertLocked(); // fails fast if the method was called without the lock
reminderService.sendDueReminders(); // normally takes about 2 minutes
}
}
// node-a 08:00:00.010 lock 'reminders' acquired, running
// node-b 08:00:00.032 lock 'reminders' is held, skipping
// node-a 08:02:05 done, lock kept until 08:01:00 at least -> released at 08:02:05
Step throughTwo nodes at 08:00
node-ashedlock tablenode-b
UPDATE ... SET lock_until = now + 10 min WHERE name = 'reminders' AND lock_until <= now
1 row updated: lock acquired
same UPDATE a few ms later
0 rows updated: skip this run
sendReminders() runs for about 2 minutes
UPDATE lock_until = max(now, locked_at + 1 min)

6 messages in order. Play them, or step through them one at a time.

The lock is a conditional UPDATE: only one node can move lock_until forward.

ShedLock applies the lock through a Spring proxy around the bean, so the usual proxy rules apply: the method must be called through the bean, not from another method in the same class. LockAssert.assertLocked() is a cheap guard that catches the mistake of calling the method directly, for example from a test or an admin endpoint.

4LockAtMostFor: The Safety Release

When a node takes the lock, it sets lock_until to now plus lockAtMostFor. Normally the node releases the lock itself when the method ends. lockAtMostFor exists for the abnormal case: the node crashes, is killed by Kubernetes or loses its network in the middle of the run. It never releases the lock, and without an expiry the job would never run again anywhere. With lockAtMostFor = PT10M, the lock expires ten minutes after it was taken, and the next scheduled execution can run on another node.

So it should be well above the normal run time, typically several times the longest run we have seen. For a job that takes 2 minutes, 10 minutes is reasonable. Setting it too short is dangerous: the lock expires while a healthy run is still working, and another node starts the same job in parallel.

5LockAtLeastFor: Protection Against Fast Jobs and Clock Skew

lockAtLeastFor sets a minimum time the lock is held, even if the job finishes sooner. On release, ShedLock does not clear the lock; it sets lock_until to the later of now and locked_at plus lockAtLeastFor.

Why would we want to hold a lock after the work is done? Because nodes' clocks are never perfectly in step. Suppose node-a's clock is 3 seconds ahead of node-b's and the job takes only 1 second. Node-a fires at its 08:00:00, runs and releases by 08:00:01 on its clock. Node-b fires at its own 08:00:00, which is 08:00:03 on node-a's clock, finds the lock free and runs the same day's job again. With lockAtLeastFor = PT1M, the lock stays taken until 08:01:00, so node-b skips. The rule of thumb is to set it longer than any plausible clock difference and shorter than the interval between runs, or the next legitimate run would be skipped too.

6What ShedLock Does Not Do

Nodes that fail to get the lock skip the execution; they do not wait, queue or retry it. If the node holding the lock fails halfway, that day's run is simply incomplete until the next scheduled time, unless the job is designed to resume. And ShedLock keeps only the current lock state, not a history of runs. This is fine for short, idempotent jobs, which is what ShedLock is designed for. Jobs that must never miss a run, or that need history and misfire handling, need a real scheduler such as clustered Quartz or a platform job.

7Follow-up questions

What happens if the job runs longer than lockAtMostFor?

The lock expires while the job is still running, and ShedLock does not stop or interrupt the running method. If another node's schedule fires after the expiry, that node can take the lock and start a second copy, so the job runs concurrently. ShedLock offers lock extension for long jobs, for example a keep-alive wrapper around the provider or extending the lock from inside the job, which keeps renewing the lock while the job is healthy; check your ShedLock version. The simpler fix is to set lockAtMostFor well above the longest run, and to keep the job idempotent so an overlap is not harmful.

Does ShedLock work with fixedRate tasks?

Yes, but think about lockAtLeastFor. With a fixedRate of 1 minute, lockAtLeastFor must be less than a minute, or every second execution would find the lock still held and skip, halving the rate.

Do I need a separate table per service?

No. Several services can share a table as long as lock names are unique across them, but most teams keep the table in each service's own database, which keeps the lock close to the data the job works on and avoids accidental name clashes.

8Conclusion

In this answer, we set up ShedLock with the shedlock table, @EnableSchedulerLock with a default lockAtMostFor and a JdbcTemplateLockProvider that uses database time, and added @SchedulerLock next to @Scheduled. We saw that the lock is a conditional update of one row, so only one node runs each execution and the others skip. lockAtMostFor is the expiry that rescues us when the lock holder dies, so it must be well above the run time, and lockAtLeastFor holds the lock for a minimum time so fast jobs and clock skew do not cause a second run.

What to say in the interviewAbout 80 seconds aloud

Open with

I add shedlock-spring and the JDBC template provider, and create the shedlock table with name as the primary key, lock_until, locked_at and locked_by. Then on a configuration class I put @EnableScheduling and @EnableSchedulerLock with defaultLockAtMostFor of PT10M, and define a LockProvider bean, a JdbcTemplateLockProvider built from the DataSource, with usingDbTime so all nodes compare against the database clock.

Then, if they want more

On the job I keep @Scheduled and add @SchedulerLock with name reminders, lockAtMostFor PT10M and lockAtLeastFor PT1M.

When the schedule fires, each node runs a conditional update on the reminders row; only one succeeds and runs the method, and the others skip that execution, they don't queue or retry. lockAtMostFor is the expiry for when the holder dies mid-run; without it the job would be locked forever, so I set it well above the normal run time, because if a healthy run outlasts it, the lock expires and another node can start a second copy. lockAtLeastFor keeps the lock for at least that long after a fast run, so a node whose clock is a few seconds behind fires, sees the lock still held, and skips. It must stay shorter than the interval between runs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Batch reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to make a @Scheduled method run on only one instance in a cluster using...": https://scrivio-interview-library.netlify.app/spring-boot/scheduling/176951f920/