@Scheduled
@Scheduled on a bean method makes the application run it by itself: every period (fixedRate), a pause after each run (fixedDelay), at cron times (cron), or once after a delay (initialDelay alone). The method takes no parameters and may return a Future.
Why
Recurring work belongs on the method that does it, with its schedule written next to it, not in a Timer started somewhere at startup. The starter also handles what is easy to forget: errors that must not stop the schedule, cancellation at shutdown, runs that take longer than their period.
Example
@Component()
class Maintenance {
// A run starts every 5 minutes, measured between starts.
@Scheduled(fixedRate: Duration(minutes: 5))
void refreshCache() => cache.refresh();
// 30 seconds after each sync has completed, Future included.
@Scheduled(fixedDelay: Duration(seconds: 30), initialDelay: Duration(seconds: 10))
Future<void> sync() => server.sync();
// 3:00 every night, UTC.
@Scheduled(cron: '0 0 3 * * *', zone: 'UTC')
Future<void> cleanup() => files.deleteOld();
// Once, a minute after the start (Spring 6.1).
@Scheduled(initialDelay: Duration(minutes: 1))
void warmUp() => cache.warmUp();
// From the configuration; off unless a profile sets the cron.
@Scheduled(cron: r'${reports.cleanup-cron:-}')
void reportCleanup() => reports.cleanup();
// Two schedules on one method.
@Scheduled(cron: '0 0 9 * * MON-FRI')
@Scheduled(cron: '0 0 11 * * SAT')
void digest() => mail.sendDigest();
}
Attributes
Give exactly one of cron, fixedRate or fixedDelay (or their *String forms). initialDelay alone, without any of them, runs the method once.
| Attribute | Meaning | Example |
|---|---|---|
fixedRate |
Start a run every period, measured between starts; runs missed during a long run or a pause of the process start back to back. | fixedRate: Duration(minutes: 5) |
fixedDelay |
Wait this long after each run completes; the one for polls and UI ticks. | fixedDelay: Duration(seconds: 30) |
initialDelay |
Wait before the first run (not with cron); alone, one run after it. |
initialDelay: Duration(seconds: 10) |
cron |
Run at cron times (see Cron expressions); - switches the task off. |
cron: '0 */15 * * * *' |
zone |
The time zone of cron: leave it out for local time, or 'UTC' (also 'Z', 'GMT'). |
zone: 'UTC' |
scheduler |
The TaskScheduler bean to run on, by qualifier or bean name (${...} allowed), when there are several. Default: the only one, the primary one or taskScheduler. |
scheduler: 'reportsScheduler' |
fixedRateString, fixedDelayString, initialDelayString |
The same as text, with ${...} placeholders and Spring Boot durations; a blank value, also once resolved, counts as not set. |
fixedRateString: r'${reports.rate:5m}' |
Durations in the text forms: 500 (milliseconds), 10s, 5m, 2h, 1d, PT1H30M.
Rules
- The method must be public and take no parameters. It may return a
Future: the run counts as finished when the future completes. - Several
@Scheduledon one method give several schedules. - Only singleton beans are scheduled;
@Scheduledon a bean of another scope, such as@Scope('prototype'), is ignored with a warning. - A wrong attribute stops the start with a message naming
Class.method: two kinds at once, none, a bad or blank cron, an unknown zone orscheduler, a missing property, a negative duration, a zerofixedRateorfixedDelay. - The method is called on the bean as other beans see it, so AOP advice (
@Around,@Cacheable...) applies.
Schedules from properties
The text attributes and cron resolve ${...} placeholders, so schedules can live in application.properties and change per profile:
# lib/resources/application.properties
reports.rate=10m
reports.cleanup-cron=0 0 3 * * *
# lib/resources/application-test.properties
reports.cleanup-cron=-
Long runs and overlapping
Everything runs on Dart's event loop, so a task never runs twice at the same time:
fixedDelay: the pause starts when the run, itsFutureincluded, completes.fixedRate: each run is due a period after the one before was due. When a run takes longer than the period (or starts late: an isolate busy with other work), the runs that came due meanwhile start one after the other right after it, until the rate is caught up, as with Spring's scheduler. A 300 ms rate whose first run takes a second starts at 0, then 1000, 1000 and 1000 ms, then 1200, 1500...cron: the next time is computed after the run, so times missed during a long run are skipped.
Fixed rate after a pause of the process
A fixed-rate task catches up after any pause, not only a long run. When a stopped process, an app suspended in the background, or a throttled browser tab runs again, every run that came due meanwhile starts at once, one after the other: a 100 ms rate after 5 seconds stopped runs about 50 times in the same millisecond. Spring's ThreadPoolTaskScheduler does the same. The pause counts as far as the system's monotonic clock counts it; time a device slept usually does not. A fixedDelay task runs once after the pause and keeps its delay; cron runs once too.
That suits work that must happen once per period. For a poll or a UI tick, where only the latest run matters, use fixedDelay.
In a Flutter app the starter stops @Scheduled tasks while the app is in the background and schedules them afresh when it comes back, so they do not catch up (unless spring.flutter.lifecycle.pause-in-background=false).
With a pool of isolates
When the web server runs a pool of isolates (server.isolates.count), every isolate runs the whole application, and so every isolate has the bean with the @Scheduled methods. By default only the application's first isolate schedules them: a job runs once for the application, not once per isolate.
# primary (the default): the first isolate only. all: every isolate.
spring.task.scheduling.isolates=all
spring.task.scheduling.isolates |
The @Scheduled methods run in |
For |
|---|---|---|
primary (default) |
the application's first isolate, main |
the nightly report, the cleanup, the poll of a queue: what must happen once |
all |
every isolate, each on its own timers | what each isolate must do for itself: refreshing what it keeps in memory |
- The setting is for all
@Scheduledmethods of the application. To run one job in every isolate and the others once, setalland put@ConditionalOnPrimaryIsolate()on the beans of the jobs that must run once. - In the other isolates the bean still exists with
primary; only its schedules are left out. Atdebugthe starter logs@Scheduled methods of Maintenance run in the primary isolate only (spring.task.scheduling.isolates=primary). - A cache refreshed by a
@Scheduledmethod is refreshed in the first isolate only withprimary: the other isolates keep their old values. That is the case forall. - Without a pool the setting changes nothing.
Shutdown
Closing the context cancels every task: no further runs start. A run going on is never interrupted. With spring.task.scheduling.shutdown.await-termination=true, the context's closeAsync() waits for the runs going on (at most await-termination-period); the synchronous close() cannot wait.
In Spring (Java)
@Scheduled(fixedDelay = 30, initialDelay = 10, timeUnit = TimeUnit.SECONDS)
void sync() { server.sync(); }
The attributes are Spring's, with Durations instead of numbers plus timeUnit. A returned Future is awaited with fixedRate and cron too, so a slow run delays the next instead of overlapping it; Spring does not wait for a returned CompletableFuture. Prototype beans are not scheduled yet.