TaskSupervisor

Struct TaskSupervisor 

Source
pub struct TaskSupervisor { /* private fields */ }
Expand description

Manages a collection of asynchronous tasks and coordinates their shutdown.

TaskSupervisor wraps TaskTracker to keep count of outstanding tasks while also exposing a process-wide CancellationToken that can be used to request cooperative shutdown.

§Examples

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

#[tokio::main]
async fn main() {
    let supervisor = TaskSupervisor::new();
     
    // Spawn a task that cooperatively handles cancellation
    let handle = supervisor.spawn_with_token(|token| async move {
        loop {
            if token.is_cancelled() {
                break;
            }
            // Do work...
            sleep(Duration::from_millis(100)).await;
        }
    });
     
    // Later, request shutdown
    supervisor.shutdown().await;
}

§Deref Implementation

TaskSupervisor implements Deref targeting TaskTracker, allowing you to call TaskTracker methods directly on a TaskSupervisor instance:

use tokio_task_supervisor::TaskSupervisor;

#[tokio::main]
async fn main() {
    let supervisor = TaskSupervisor::new();
     
    // These calls work through deref coercion:
    let handle = supervisor.spawn(async { 42 });
    let count = supervisor.len();
    let is_closed = supervisor.is_closed();
     
    // Equivalent to:
    let handle = supervisor.tracker().spawn(async { 42 });
    let count = supervisor.tracker().len();
    let is_closed = supervisor.tracker().is_closed();
}

Implementations§

Source§

impl TaskSupervisor

Source

pub fn new() -> Self

Creates a new task manager.

Source

pub fn tracker(&self) -> &TaskTracker

Returns a reference to the underlying TaskTracker.

Source

pub fn token(&self) -> CancellationToken

Returns a clone of the shared cancellation token.

Source

pub fn cancel_on_drop(&self) -> DropGuardRef<'_>

Returns a guard that cancels the shutdown token when dropped.

Source

pub fn is_cancelled(&self) -> bool

Returns true if the shutdown token has been cancelled.

Source

pub fn is_closed(&self) -> bool

Returns true if the task tracker is closed.

Source

pub fn len(&self) -> usize

Returns the number of outstanding tasks.

Source

pub fn wait(&self) -> TaskTrackerWaitFuture<'_>

Returns a future that completes when all tasks finish.

Source

pub fn cancel(&self)

Cancels the shared shutdown token.

Tasks spawned through the managed API can observe this and exit cooperatively.

Source

pub async fn shutdown(&self)

Initiates graceful shutdown by closing the tracker and cancelling all tasks.

This method will:

  1. Close the task tracker to prevent new tasks from being spawned
  2. Cancel the shutdown token to signal all existing tasks
  3. Wait for all tasks to complete
Source

pub async fn shutdown_with_timeout( &self, timeout: Duration, ) -> Result<(), Elapsed>

Initiates graceful shutdown with a timeout.

§Arguments
  • timeout - Maximum time to wait for shutdown to complete
§Returns
  • Ok(()) if shutdown completed within the timeout
  • Err(Elapsed) if the timeout was exceeded
Source

pub fn spawn_with_cancel<F, Fut>( &self, task: F, ) -> JoinHandle<CancelOutcome<Fut::Output>>
where F: FnOnce() -> Fut + Send + 'static, Fut: Future + Send + 'static, Fut::Output: Send + 'static,

Spawns a task that races against the shared cancellation token.

The returned future resolves with CancelOutcome, indicating whether the task finished normally or was cancelled. When cancellation wins the race, the task future is dropped, so it should not rely on Drop for cleanup.

§Arguments
  • task - A closure that returns the future to execute
§Returns

A JoinHandle that resolves to the task’s outcome

Source

pub fn spawn_on_with_cancel<F, Fut>( &self, task: F, handle: &Handle, ) -> JoinHandle<CancelOutcome<Fut::Output>>
where F: FnOnce() -> Fut + Send + 'static, Fut: Future + Send + 'static, Fut::Output: Send + 'static,

Spawns a task with cancellation handling on a specific runtime handle.

§Arguments
  • task - A closure that returns the future to execute
  • handle - The runtime handle to spawn the task on
§Returns

A JoinHandle that resolves to the task’s outcome

Source

pub fn spawn_local_with_cancel<F, Fut>( &self, task: F, ) -> JoinHandle<CancelOutcome<Fut::Output>>
where F: FnOnce() -> Fut + 'static, Fut: Future + 'static, Fut::Output: 'static,

Spawns a !Send task that races against the shared cancellation token.

§Arguments
  • task - A closure that returns the future to execute
§Returns

A JoinHandle that resolves to the task’s outcome

Source

pub fn spawn_local_on_with_cancel<F, Fut>( &self, task: F, local_set: &LocalSet, ) -> JoinHandle<CancelOutcome<Fut::Output>>
where F: FnOnce() -> Fut + 'static, Fut: Future + 'static, Fut::Output: 'static,

Spawns a !Send task on a LocalSet with cancellation handling.

§Arguments
  • task - A closure that returns the future to execute
  • local_set - The local set to spawn the task on
§Returns

A JoinHandle that resolves to the task’s outcome

Source

pub fn spawn_with_token<F, Fut>(&self, task: F) -> JoinHandle<Fut::Output>
where F: FnOnce(CancellationToken) -> Fut + Send + 'static, Fut: Future + Send + 'static, Fut::Output: Send + 'static,

Spawns a task that receives the shared cancellation token.

§Arguments
  • task - A closure that takes a cancellation token and returns a future
§Returns

A JoinHandle that resolves to the task’s output

Source

pub fn spawn_on_with_token<F, Fut>( &self, task: F, handle: &Handle, ) -> JoinHandle<Fut::Output>
where F: FnOnce(CancellationToken) -> Fut + Send + 'static, Fut: Future + Send + 'static, Fut::Output: Send + 'static,

Spawns a task with the shared cancellation token on a specific runtime handle.

§Arguments
  • task - A closure that takes a cancellation token and returns a future
  • handle - The runtime handle to spawn the task on
§Returns

A JoinHandle that resolves to the task’s output

Source

pub fn spawn_local_with_token<F, Fut>(&self, task: F) -> JoinHandle<Fut::Output>
where F: FnOnce(CancellationToken) -> Fut + 'static, Fut: Future + 'static, Fut::Output: 'static,

Spawns a local task that receives the shared cancellation token.

§Arguments
  • task - A closure that takes a cancellation token and returns a future
§Returns

A JoinHandle that resolves to the task’s output

Source

pub fn spawn_local_on_with_token<F, Fut>( &self, task: F, local_set: &LocalSet, ) -> JoinHandle<Fut::Output>
where F: FnOnce(CancellationToken) -> Fut + 'static, Fut: Future + 'static, Fut::Output: 'static,

Spawns a local task with a cancellation token on a specific local set.

§Arguments
  • task - A closure that takes a cancellation token and returns a future
  • local_set - The local set to spawn the task on
§Returns

A JoinHandle that resolves to the task’s output

Source

pub fn spawn_blocking_with_token<F, T>(&self, task: F) -> JoinHandle<T>
where F: FnOnce(CancellationToken) -> T + Send + 'static, T: Send + 'static,

Spawns a blocking task that receives a cancellation context.

§Arguments
  • task - A closure that takes a cancellation token and returns a value
§Returns

A JoinHandle that resolves to the task’s output

Source

pub fn spawn_blocking_on_with_token<F, T>( &self, task: F, handle: &Handle, ) -> JoinHandle<T>
where F: FnOnce(CancellationToken) -> T + Send + 'static, T: Send + 'static,

Spawns a blocking task with context on a specific runtime handle.

§Arguments
  • task - A closure that takes a cancellation token and returns a value
  • handle - The runtime handle to spawn the task on
§Returns

A JoinHandle that resolves to the task’s output

Methods from Deref<Target = TaskTracker>§

Source

pub fn wait(&self) -> TaskTrackerWaitFuture<'_>

Waits until this TaskTracker is both closed and empty.

If the TaskTracker is already closed and empty when this method is called, then it returns immediately.

The wait future is resistant against ABA problems. That is, if the TaskTracker becomes both closed and empty for a short amount of time, then it is guarantee that all wait futures that were created before the short time interval will trigger, even if they are not polled during that short time interval.

§Cancel safety

This method is cancel safe.

However, the resistance against ABA problems is lost when using wait as the condition in a tokio::select! loop.

Source

pub fn close(&self) -> bool

Close this TaskTracker.

This allows wait futures to complete. It does not prevent you from spawning new tasks.

Returns true if this closed the TaskTracker, or false if it was already closed.

Source

pub fn reopen(&self) -> bool

Reopen this TaskTracker.

This prevents wait futures from completing even if the TaskTracker is empty.

Returns true if this reopened the TaskTracker, or false if it was already open.

Source

pub fn is_closed(&self) -> bool

Returns true if this TaskTracker is closed.

Source

pub fn len(&self) -> usize

Returns the number of tasks tracked by this TaskTracker.

Source

pub fn is_empty(&self) -> bool

Returns true if there are no tasks in this TaskTracker.

Source

pub fn spawn<F>(&self, task: F) -> JoinHandle<<F as Future>::Output>
where F: Future + Send + 'static, <F as Future>::Output: Send + 'static,

Spawn the provided future on the current Tokio runtime, and track it in this TaskTracker.

This is equivalent to tokio::spawn(tracker.track_future(task)).

Source

pub fn spawn_on<F>( &self, task: F, handle: &Handle, ) -> JoinHandle<<F as Future>::Output>
where F: Future + Send + 'static, <F as Future>::Output: Send + 'static,

Spawn the provided future on the provided Tokio runtime, and track it in this TaskTracker.

This is equivalent to handle.spawn(tracker.track_future(task)).

Source

pub fn spawn_local<F>(&self, task: F) -> JoinHandle<<F as Future>::Output>
where F: Future + 'static, <F as Future>::Output: 'static,

Spawn the provided future on the current LocalSet, and track it in this TaskTracker.

This is equivalent to tokio::task::spawn_local(tracker.track_future(task)).

Source

pub fn spawn_local_on<F>( &self, task: F, local_set: &LocalSet, ) -> JoinHandle<<F as Future>::Output>
where F: Future + 'static, <F as Future>::Output: 'static,

Spawn the provided future on the provided LocalSet, and track it in this TaskTracker.

This is equivalent to local_set.spawn_local(tracker.track_future(task)).

Source

pub fn spawn_blocking<F, T>(&self, task: F) -> JoinHandle<T>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static,

Spawn the provided blocking task on the current Tokio runtime, and track it in this TaskTracker.

This is equivalent to tokio::task::spawn_blocking(tracker.track_future(task)).

Source

pub fn spawn_blocking_on<F, T>(&self, task: F, handle: &Handle) -> JoinHandle<T>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static,

Spawn the provided blocking task on the provided Tokio runtime, and track it in this TaskTracker.

This is equivalent to handle.spawn_blocking(tracker.track_future(task)).

Source

pub fn track_future<F>(&self, future: F) -> TrackedFuture<F>
where F: Future,

Track the provided future.

The returned TrackedFuture will count as a task tracked by this collection, and will prevent calls to wait from returning until the task is dropped.

The task is removed from the collection when it is dropped, not when poll returns Poll::Ready.

§Examples

Track a future spawned with tokio::spawn.

use tokio_util::task::TaskTracker;

let tracker = TaskTracker::new();

tokio::spawn(tracker.track_future(my_async_fn()));

Track a future spawned on a JoinSet.

use tokio::task::JoinSet;
use tokio_util::task::TaskTracker;

let tracker = TaskTracker::new();
let mut join_set = JoinSet::new();

join_set.spawn(tracker.track_future(my_async_fn()));
Source

pub fn token(&self) -> TaskTrackerToken

Creates a TaskTrackerToken representing a task tracked by this TaskTracker.

This token is a lower-level utility than the spawn methods. Each token is considered to correspond to a task. As long as the token exists, the TaskTracker cannot complete. Furthermore, the count returned by the len method will include the tokens in the count.

Dropping the token indicates to the TaskTracker that the task has exited.

Trait Implementations§

Source§

impl Clone for TaskSupervisor

Source§

fn clone(&self) -> TaskSupervisor

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for TaskSupervisor

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Deref for TaskSupervisor

Source§

type Target = TaskTracker

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.