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;
}

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

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

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<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.