pub struct TaskMonitor { /* private fields */ }Expand description
A monitor for spawning and monitoring background tasks.
The TaskMonitor allows you to spawn background tasks that are
automatically monitored for panics, errors, and unexpected termination.
In such cases, a BackgroundTaskFailure is sent through a broadcast
channel that subscribers can listen to.
§Example
use matrix_sdk_common::task_monitor::TaskMonitor;
let monitor = TaskMonitor::new();
// Subscribe to failures
let mut failures = monitor.subscribe();
// Spawn a task that runs indefinitely
let _handle = monitor.spawn_background_task("worker", async {
loop {
// Do work...
matrix_sdk_common::sleep::sleep(std::time::Duration::from_secs(1))
.await;
}
});Implementations§
Source§impl TaskMonitor
impl TaskMonitor
Sourcepub fn subscribe(&self) -> Receiver<BackgroundTaskFailure>
pub fn subscribe(&self) -> Receiver<BackgroundTaskFailure>
Subscribe to failure notifications.
Returns a broadcast receiver that will receive BackgroundTaskFailure
messages whenever a monitored task fails.
Note: If the receiver falls behind, older messages may be dropped.
Sourcepub fn spawn_background_task<F>(
&self,
name: impl Into<String>,
future: F,
) -> BackgroundTaskHandle
pub fn spawn_background_task<F>( &self, name: impl Into<String>, future: F, ) -> BackgroundTaskHandle
Spawn a background task that is expected to run indefinitely.
If the task completes (whether successfully or by panicking), it will be
reported as a BackgroundTaskFailure report through the broadcast
channel.
Use this for long-running tasks like event loops, sync tasks, or background workers that should never complete under normal operation.
§Arguments
name- A human-readable name for the task (for debugging purposes).future- The async task to run.
§Returns
A BackgroundTaskHandle that can be used to abort the task or check
if it has finished. This is the equivalent of tokio’s JoinHandle.
Sourcepub fn spawn_fallible_task<F, E>(
&self,
name: impl Into<String>,
future: F,
) -> BackgroundTaskHandlewhere
F: Future<Output = Result<(), E>> + SendOutsideWasm + 'static,
E: Error + SendOutsideWasm + 'static,
pub fn spawn_fallible_task<F, E>(
&self,
name: impl Into<String>,
future: F,
) -> BackgroundTaskHandlewhere
F: Future<Output = Result<(), E>> + SendOutsideWasm + 'static,
E: Error + SendOutsideWasm + 'static,
Spawn a background task that returns a Result.
The task is monitored for panics and errors; see also
BackgroundTaskFailure.
If the task returns Ok(()), it is considered successful and no failure
is reported.
§Arguments
name- A human-readable name for the task (for debugging purposes).future- The async task to run.
§Returns
A BackgroundTaskHandle that can be used to abort the task or check
if it has finished. This is the equivalent of tokio’s JoinHandle.