Sub topic 3
Fixed rate, fixed delay and initial delay
This chapter covers the three interval-based trigger attributes of @Scheduled. It assumes you can already enable scheduling with @EnableScheduling and put @Scheduled on a no-argument method of a Spring bean. It also assumes you know that a thread runs one piece of code at a time. Cron expressions are covered in the next chapter.
Three attributes, three questions
Interval triggers answer two questions: when does the next run start, and when does the first run start?
fixedRateruns the task at a constant interval measured between start times.fixedDelaywaits a constant interval measured from the end of one run to the start of the next.initialDelaypostpones the first run. It does not change the interval after that.
Each @Scheduled annotation takes exactly one of fixedRate, fixedDelay or cron. Combining them throws an IllegalStateException when the bean is processed at startup, so the application fails to start.
@Scheduled(fixedRate = 5000)
public void pollEveryFiveSeconds() { }
@Scheduled(fixedDelay = 5000, initialDelay = 10000)
public void pauseBetweenRuns() { }By default the values are in milliseconds. Since Spring 5.3.10 you can change the unit with timeUnit, which applies to all three attributes:
@Scheduled(fixedRate = 5, initialDelay = 1, timeUnit = TimeUnit.MINUTES)
public void everyFiveMinutes() { }fixedRate: constant start-to-start spacing
With fixedRate = 2000, Spring aims to start the task at 0 s, 2 s, 4 s, 6 s and so on. The schedule is computed from the first start time. It does not depend on how long each run takes.
Use fixedRate when the cadence matters more than the pause between runs. Examples are a heartbeat, sampling a metric every 10 seconds, or refreshing a cache that goes stale on a clock.
The scheduler never runs the same @Scheduled method concurrently with itself, unless you add @Async (a later chapter). So what happens when a run takes longer than the rate? The next run cannot start until the current one finishes. After that, the scheduler tries to catch up on the start times it missed. The late runs start back to back until the schedule is current again.
fixedDelay: constant pause between runs
With fixedDelay = 2000, Spring waits 2 seconds after each run completes, then starts the next one. The gap between runs stays the same no matter how long the work takes.
Use fixedDelay when runs must not crowd each other and each run should get a rest. Examples are polling a queue, calling a rate-limited API, or processing a backlog. If a run takes 30 seconds, the next one starts 2 seconds after that, with no catch-up burst.
Seeing the difference
The following class has one task per trigger. Each task sleeps for 3 seconds to simulate work that is slower than the 2-second interval. It prints seconds since startup so the spacing is visible.
package com.example.demo;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TimingDemo {
private static final Logger log = LoggerFactory.getLogger(TimingDemo.class);
private final long startedAt = System.currentTimeMillis();
@Scheduled(fixedRate = 2000)
public void rate() throws InterruptedException {
log.info("rate started at t={}s", elapsedSeconds());
TimeUnit.SECONDS.sleep(3);
}
@Scheduled(fixedDelay = 2000)
public void delay() throws InterruptedException {
log.info("delay started at t={}s", elapsedSeconds());
TimeUnit.SECONDS.sleep(3);
}
private long elapsedSeconds() {
return (System.currentTimeMillis() - startedAt) / 1000;
}
}Spring Boot's scheduler has one thread by default, so these two tasks would delay each other. Give each task its own thread so the comparison is clean:
spring:
task:
scheduling:
pool:
size: 2The approximate start times, in seconds after the first run, are:
| Run | `fixedRate = 2000` | `fixedDelay = 2000` |
|---|---|---|
| 1 | 0 | 0 |
| 2 | 3 | 5 |
| 3 | 6 | 10 |
| 4 | 9 | 15 |
The rate task wanted to start at 0, 2, 4 and 6 seconds. Because each run takes 3 seconds, each run starts the moment the previous one ends, at 0, 3, 6 and 9. The delay task always waits 2 seconds after a 3-second run, so it starts every 5 seconds.
initialDelay: postponing the first run
Without initialDelay, an interval task runs for the first time as soon as the application context has finished starting. The first run is not delayed for either fixedRate or fixedDelay.
initialDelay is useful in three situations:
- The task depends on something that finishes warming up shortly after startup, such as caches or a connection pool.
- You want several tasks not to all fire at second zero. Stagger them with different initial delays.
- A restart-heavy environment (rolling deploys, autoscaling) should not hammer a downstream service every time a pod boots.
With fixedRate, the initial delay sets the first start time, and every later start is spaced from it. @Scheduled(fixedRate = 60000, initialDelay = 15000) starts at 15 s, 75 s, 135 s and so on. With fixedDelay, the initial delay only postpones the first run. After that, the pause is measured from the end of each run.
The attribute does not work with cron. Spring rejects initialDelay on a cron trigger at startup, because a cron expression already defines exactly when the first run happens.
String variants and durations
Each numeric attribute has a String twin: fixedRateString, fixedDelayString and initialDelayString. They accept property placeholders (covered in a later chapter), plain milliseconds such as "5000", and ISO-8601 durations such as "PT30S" for 30 seconds or "PT5M" for 5 minutes.
@Scheduled(fixedDelayString = "PT30S", initialDelayString = "PT10S")
public void readableDurations() { }Use either the numeric or the String variant of one attribute, not both. Declaring fixedRate and fixedRateString together fails at startup.
Failure modes and edge cases
A slow task on the shared thread. The default pool has one thread. A fixedRate task that runs longer than its interval will start late. A long fixedDelay task still occupies the only thread and holds up every other scheduled task. The thread pool chapter covers the fix.
Catch-up bursts. After a long stall in a fixedRate task, such as a slow database call or a JVM pause, you may see several runs in quick succession. If the task is not safe to run back to back, prefer fixedDelay.
Exceptions do not cancel the schedule. If a run throws, Spring logs the error and the task is still scheduled again. A fixedDelay task is rescheduled after the failed run ends. Error handling gets its own chapter.
Intervals ignore the wall clock. Fixed intervals count elapsed time, so daylight saving changes do not shift them. This is good for "every 10 seconds" and wrong for "every day at 02:00". Use cron for the second case.
Return values are ignored. The annotated method should be void. A returned value is discarded, and the method may not take parameters.
Choosing between them
| Requirement | Choice |
|---|---|
| Sample or send something at a steady cadence | `fixedRate` |
| Runs must not queue up or run back to back | `fixedDelay` |
| Wait for the system to warm up before the first run | add `initialDelay` |
| Run at a particular time of day or week | `cron` (next chapter) |
If you are unsure, start with fixedDelay. It cannot produce a catch-up burst, and its worst case is a run that starts a bit later than you expected.
Exercise
A task is annotated with @Scheduled(fixedRate = 10000), runs on the default single scheduler thread, and each run takes 25 seconds. At what times (in seconds after the first start) do the first four runs start, and how would the pattern change with fixedDelay = 10000?
Show answer
With fixedRate the runs start at 0, 25, 50 and 75 seconds. The task wanted to start at 0, 10, 20 and so on, but a run cannot start until the previous one ends, so each run starts as soon as the last one finishes. With fixedDelay = 10000 the runs start at 0, 35, 70 and 105 seconds, because 10 seconds are added after each 25-second run.
Exercise
You want a task to run every 5 minutes, but the first run should happen 1 minute after startup, and the interval should be easy to read in the source. Write the annotation. Why can't you add initialDelay to a cron-based @Scheduled?
Show answer
@Scheduled(fixedRate = 5, initialDelay = 1, timeUnit = TimeUnit.MINUTES), or equivalently @Scheduled(fixedRateString = "PT5M", initialDelayString = "PT1M"). A cron expression already fixes exactly which instants the task runs at, so there is no "first run after startup" to postpone, and Spring rejects the combination at startup.