@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

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:

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

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.

See also