Expand description
Task supervisor for managing supervised async tasks.
The TaskSupervisor is a specialized version of DynamicSupervisor that makes it easy
to run async tasks (futures) under supervision. It wraps each task in a lightweight actor that can be monitored
and restarted according to the configured policy.
§Use Cases
The TaskSupervisor is ideal for:
- Background jobs that need supervision
- Periodic tasks that should be restarted on failure
- Long-running async operations that need monitoring
- Any async work that should be part of your supervision tree
§Key Features
- Simple API: Wrap any async task in supervision with minimal boilerplate
- Full Supervision: Tasks get all the benefits of actor supervision
- Flexible Policies: Control restart behavior via TaskOptions
- Resource Control: Inherit max_childrenand other limits fromDynamicSupervisor
§Example
use ractor_supervisor::*;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
    // Configure the task supervisor
    let options = TaskSupervisorOptions {
        max_children: Some(10),
        max_restarts: 3,
        max_seconds: 10,
        restart_counter_reset_after: Some(30),
    };
    // Spawn the supervisor
    let (sup_ref, _) = TaskSupervisor::spawn(
        "task-sup".into(),
        options
    ).await.unwrap();
    // Define a task that might fail
    let task_id = TaskSupervisor::spawn_task(
        sup_ref.clone(),
        || async {
            // Simulate some work
            sleep(Duration::from_secs(1)).await;
             
            // Maybe fail sometimes...
            if rand::random() {
                panic!("Random failure!");
            }
 
            Ok(())
        },
        TaskOptions::new()
            .name("periodic-job".into())
            .restart_policy(Restart::Permanent)
    ).await.unwrap();
    // Later, stop the task if needed
    TaskSupervisor::terminate_task(sup_ref, task_id).await.unwrap();
    ()
}§Task Lifecycle
- 
When you call TaskSupervisor::spawn_task:- Your async task is wrapped in a TaskActor
- The actor is spawned under the supervisor
- The task starts executing immediately
 
- Your async task is wrapped in a 
- 
If the task completes normally: - The actor stops normally
- If policy is Restart::Permanent, it’s restarted
- If policy is Restart::TransientorRestart::Temporary, it’s not restarted
 
- 
If the task panics: - The actor fails abnormally
- If policy is Restart::PermanentorRestart::Transient, it’s restarted
- If policy is Restart::Temporary, it’s not restarted
 
- 
Restart behavior is controlled by: - The TaskOptions::restart_policy
- The supervisor’s meltdown settings
- Any configured backoff delays
 
- The 
Structs§
- TaskActor 
- Actor that wraps and executes an async task.
- TaskFn
- A wrapped async task that can be executed by a TaskActor.
- TaskOptions 
- TaskSupervisor 
Enums§
- TaskActor Message 
- Messages that can be sent to a TaskActor.