Expand description
This module provides a TaskMonitor for spawning and monitoring
long-running background tasks. Tasks spawned through the monitor are
monitored for panics, errors, and unexpected termination.
use matrix_sdk_common::task_monitor::TaskMonitor;
let monitor = TaskMonitor::new();
// Subscribe to failure notifications
let mut failures = monitor.subscribe();
// Spawn a monitored background task
let handle = monitor.spawn_background_task("my_task", async {
loop {
// Do background work...
matrix_sdk_common::sleep::sleep(std::time::Duration::from_secs(1))
.await;
}
});
// It's also possible to have the task be aborted safely (and without a report)
// when the handle is dropped.
let _handle = handle.abort_on_drop();
// Listen for failures in another task
// while let Ok(failure) = failures.recv().await {
// eprintln!("Task {} failed: {:?}", failure.task.name, failure.reason);
// }§A word about unwind safety
This assumes that all the code running inside the monitored tasks is unwind safe. The assumption is that these are long-running tasks that:
- should not panic under normal operation,
- will not be automatically restarted with state shared previously (they can be restarted, but in this case they have to be restarted with a clean state).
In general, observers of the task monitor should consider any reported failure as fatal, and they may decide to report the error one way or another (e.g., logging, metrics) and subsequently crash the process to avoid running in a potentially corrupted state.
§WebAssembly (WASM) support
Unfortunately, safe unwinding isn’t supported on most WASM targets, as of 2026-01-28, so panics in monitored tasks cannot be caught and reported. Instead, a panic in a monitored task may throw a JS exception. The rest of the monitoring features (error reporting, early termination) is still functional, though.
Structs§
- Background
Task Failure - A report of a background task failure.
- Background
Task Handle - A handle to a spawned background task.
- Background
Task Info - Metadata about a spawned background task.
- TaskId
- Unique identifier for a background task.
- Task
Monitor - A monitor for spawning and monitoring background tasks.
Enums§
- Background
Task Failure Reason - Reason why a background task failed.