BackgroundTasks class final
Work that outlives the response that started it.
Sending a receipt, warming a cache, writing an audit row: things a caller should not wait for, and that still have to finish.
The reason this exists rather than a bare unawaited(...): shutdown counts
requests, so work spawned outside one is invisible to it. On every
deploy that work is killed mid-flight, and nothing logs it — a customer gets
a 201 and never gets their email, with no trace of why. A task registered
here is drained with everything else.
final tasks = BackgroundTasks();
final server = await serve(app, address, 8080, background: tasks);
Future<Order> checkout(Request request) async {
final order = await shop.place(basket);
final tasks = await request.state<BackgroundTasks>();
tasks.run('receipt', () => mail.sendReceipt(order));
return order;
}
This is in-process and unpersisted. A task lost to a crash is gone, and it does not retry. That is the right shape for work that is nice to finish and the wrong one for work that must happen — an outbox table or a real queue is the answer there, and this is not a substitute for one.
Constructors
- BackgroundTasks({void onError(Object error, StackTrace stack)?})
- Creates an empty registry.
Properties
Methods
-
close(
{Duration within = const Duration(seconds: 15)}) → Future< bool> -
Stops accepting new tasks, then waits
withinfor the running ones. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
run(
String name, Future< void> body()) → bool -
Runs
bodyin the background, tracked so shutdown waits for it. -
settled(
Duration within) → Future< bool> -
Waits
withinfor the running tasks without closing the registry. -
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited