Module task

Source
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

  1. Simple API: Wrap any async task in supervision with minimal boilerplate
  2. Full Supervision: Tasks get all the benefits of actor supervision
  3. Flexible Policies: Control restart behavior via TaskOptions
  4. Resource Control: Inherit max_children and other limits from DynamicSupervisor

§Example

use ractor_supervisor::*;
use ractor::concurrency::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_window: Duration::from_secs(10),
        reset_after: Some(Duration::from_secs(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

  1. 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
  2. If the task completes normally:

  3. If the task panics:

  4. Restart behavior is controlled by:

Structs§

TaskActor
Actor that wraps and executes an async task.
TaskFn
A wrapped async task that can be executed by a TaskActor.
TaskOptions
Options for configuring a task to be supervised.
TaskSupervisor

Enums§

TaskActorMessage
Messages that can be sent to a TaskActor.

Type Aliases§

TaskSupervisorMsg
TaskSupervisorOptions