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

hashCode → int
The hash code for this object.
no setterinherited
isClosed → bool
Whether the registry has stopped accepting work.
no setter
pending → int
How many tasks are running right now.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

close({Duration within = const Duration(seconds: 15)}) → Future<bool>
Stops accepting new tasks, then waits within for 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 body in the background, tracked so shutdown waits for it.
settled(Duration within) → Future<bool>
Waits within for 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