#async-task #tokio #tokio-task #cancellation

tokio-task-supervisor

Tokio TaskTracker with built-in cancellation token management and coordinated shutdown

2 releases

0.1.1 Oct 12, 2025
0.1.0 Oct 12, 2025

#1139 in Asynchronous

MIT license

24KB
370 lines

tokio-task-supervisor

A wrapper around tokio_util::task::TaskTracker that adds coordinated shutdown via a shared cancellation token.

What it does

  • Tracks running tasks (same as TaskTracker)
  • Provides a shared CancellationToken for shutdown
  • Spawns tasks that automatically get cancellation tokens
  • Handles graceful shutdown (close tracker + cancel token + wait)

Usage

use tokio_task_supervisor::TaskSupervisor;
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let supervisor = TaskSupervisor::new();

    // Spawn tasks that can be cancelled
    let handle = supervisor.spawn_with_token(|token| async move {
        loop {
            tokio::select! {
                _ = token.cancelled() => break,
                _ = sleep(Duration::from_millis(100)) => {}
            }
        }
    });

    // Shutdown all tasks
    supervisor.shutdown().await;
    handle.await.expect("task finished");
}

API

  • spawn_with_token() - spawn task with cancellation token
  • spawn_with_cancel() - spawn task that races against cancellation
  • shutdown() - cancel all tasks and wait for completion

License

MIT

Dependencies

~3–6.5MB
~115K SLoC