TaskScheduler
@Scheduled covers work known when the code is written. When the schedule is decided at runtime (a reminder at a time the user picked, a poll that runs while a screen is open, a cron a user typed), inject the TaskScheduler bean and schedule the work in code. Each call returns a ScheduledTask you can inspect and cancel.
Why
Timers started by hand must be kept, cancelled and guarded against errors. The scheduler does this the same way as for @Scheduled: errors are logged without stopping the schedule, tasks are cancelled when the context closes, and fixed-rate tasks catch up after a long run.
Example
@Service()
class Reminders {
Reminders(this.scheduler);
final TaskScheduler scheduler;
// At the time the user picked in the app.
ScheduledTask remindAt(DateTime at, String text) =>
scheduler.scheduleAt(() => notify(text), at, name: 'reminder');
// While the inbox screen is open; the caller cancels the task.
ScheduledTask poll() => scheduler.scheduleWithFixedDelay(
checkInbox,
const Duration(seconds: 30),
);
// A cron the user typed, checked first.
ScheduledTask custom(String expression) => scheduler.schedule(
exportReport,
CronTrigger(CronExpression.parse(expression)),
);
}
final task = reminders.poll();
final due = task.nextExecution; // when the next run is due
task.cancel(); // the screen closed
Methods
| Method | Runs the task |
|---|---|
scheduleAt(task, time, name:) |
Once at time, or right away when it has passed. |
scheduleAtFixedRate(task, period, initialDelay:, name:) |
Every period, measured between starts; after a pause of the process, every missed run at once. |
scheduleWithFixedDelay(task, delay, initialDelay:, name:) |
Again and again, delay after each run has finished. |
schedule(task, trigger, name:) |
At the times a Trigger gives. |
A task is a function that may return a Future; the run counts as finished when it completes.
ScheduledTask
| Member | Meaning |
|---|---|
name |
The task's name, in logs. |
trigger |
Its trigger. |
nextExecution |
When the next run is due, or null. |
runs |
The number of runs so far. |
isCancelled |
Whether it was cancelled. |
cancel() |
No further run starts; a run going on finishes. |
Triggers
| Trigger | Gives |
|---|---|
PeriodicTrigger(period, fixedRate:, initialDelay:) |
Every period, between starts with fixedRate: true, else from the end of a run. Runs as scheduleAtFixedRate or scheduleWithFixedDelay do, on the task's own timeline. |
CronTrigger(expression, utc:) |
The times of a CronExpression, in local time or UTC. |
OneShotTrigger |
One time. |
| your own | nextExecution(context): the next time, or null to end the task. |
A trigger of your own, for a schedule the others cannot express:
// Polls quickly at first, then backs off up to every 10 minutes.
final class BackOff implements Trigger {
var _delay = const Duration(seconds: 5);
@override
DateTime? nextExecution(TriggerContext context) {
final next = (context.lastCompletion ?? context.now).add(_delay);
if (_delay < const Duration(minutes: 10)) {
_delay *= 2;
}
return next;
}
}
scheduler.schedule(checkInbox, BackOff());
TriggerContext has now, lastScheduledExecution, lastActualExecution and lastCompletion.
In a Flutter app
Tasks started with a TaskScheduler keep their schedule in the background (only @Scheduled tasks are paused there). Cancel them when their screen goes away, or give them a fixed delay, so they do not catch up when the app comes back:
// A countdown on screen: back from the background it ticks once.
final tick = scheduler.scheduleWithFixedDelay(refreshCountdown, const Duration(seconds: 1));
The scheduler bean
The starter's scheduler is a TimerTaskScheduler. Declare your own TaskScheduler bean to replace it.
With several TaskScheduler beans, @Scheduled methods run on the primary one or the one named taskScheduler, unless they name another with scheduler:. When neither exists, the start fails; Spring would fall back to a local single-threaded scheduler.
TimerTaskScheduler(now:, createTimer:, awaitTermination:, awaitTerminationPeriod:, errorHandler:) takes a clock and a timer factory for tests (see Testing and time). runningTasks lists the runs going on. A scheduler of your own can wait at shutdown through a destroy() that returns a Future (DisposableBean).
In Spring (Java)
ScheduledFuture<?> task = scheduler.schedule(() -> notify(text), Instant.parse(at));
schedule(task, Instant) is scheduleAt(task, DateTime) here (Dart has no overloads), and a ScheduledTask replaces ScheduledFuture. A PeriodicTrigger runs on the task's timeline; Spring plans it with the wall clock. SchedulingConfigurer and ScheduledTaskRegistrar are not here yet.