# tokio_util::sync::CancellationToken - Rust
API documentation for the Rust `CancellationToken` struct in crate `tokio_util`.
Keywords: rust, rustlang, rust-lang, CancellationToken

# Struct tokio_util::sync::CancellationToken [−] [src]

    pub struct CancellationToken { /* fields omitted */ }

A token which can be used to signal a cancellation request to one or more tasks.

Tasks can call `CancellationToken::cancelled()` in order to obtain a Future which will be resolved when cancellation is requested.

Cancellation can be requested through the `CancellationToken::cancel` method.

# Examples

ⓘ

    use tokio::select;
    use tokio::scope::CancellationToken;

    #[tokio::main]
    async fn main() {
        let token = CancellationToken::new();
        let cloned_token = token.clone();

        let join_handle = tokio::spawn(async move {
            // Wait for either cancellation or a very long time
            select! {
                _ = cloned_token.cancelled() => {
                    // The token was cancelled
                    5
                }
                _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
                    99
                }
            }
        });

        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            token.cancel();
        });

        assert_eq!(5, join_handle.await.unwrap());
    }

## Implementations

### `impl CancellationToken` [src]

#### `pub fn new() -> CancellationToken` [src]

Creates a new CancellationToken in the non-cancelled state.

#### `pub fn child_token(&self) -> CancellationToken` [src]

Creates a `CancellationToken` which will get cancelled whenever the current token gets cancelled.

If the current token is already cancelled, the child token will get returned in cancelled state.

# Examples

ⓘ

    use tokio::select;
    use tokio::scope::CancellationToken;

    #[tokio::main]
    async fn main() {
        let token = CancellationToken::new();
        let child_token = token.child_token();

        let join_handle = tokio::spawn(async move {
            // Wait for either cancellation or a very long time
            select! {
                _ = child_token.cancelled() => {
                    // The token was cancelled
                    5
                }
                _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
                    99
                }
            }
        });

        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            token.cancel();
        });

        assert_eq!(5, join_handle.await.unwrap());
    }

#### `pub fn cancel(&self)` [src]

Cancel the `CancellationToken` and all child tokens which had been derived from it.

This will wake up all tasks which are waiting for cancellation.

#### `pub fn is_cancelled(&self) -> bool` [src]

Returns `true` if the `CancellationToken` had been cancelled

#### `pub fn cancelled(&self) -> WaitForCancellationFuture<'_>ⓘ

### Notable traits for WaitForCancellationFuture<'a>

`impl<'a> Future for WaitForCancellationFuture<'a> type Output = ();`
` [src]

Returns a `Future` that gets fulfilled when cancellation is requested.

## Trait Implementations

### `impl Clone for CancellationToken` [src]

#### `fn clone(&self) -> Self` [src]

Returns a copy of the value. Read more

#### `pub fn clone_from(&mut self, source: &Self)`1.0.0 [src]

Performs copy-assignment from `source`. Read more

### `impl Debug for CancellationToken` [src]

#### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` [src]

Formats the value using the given formatter. Read more

### `impl Default for CancellationToken` [src]

#### `fn default() -> CancellationToken` [src]

Returns the "default value" for a type. Read more

### `impl Drop for CancellationToken` [src]

#### `fn drop(&mut self)` [src]

Executes the destructor for this type. Read more

### `impl Send for CancellationToken` [src]

### `impl Sync for CancellationToken` [src]

## Auto Trait Implementations

### `impl RefUnwindSafe for CancellationToken` [src]

### `impl Unpin for CancellationToken` [src]

### `impl UnwindSafe for CancellationToken` [src]

## Blanket Implementations

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `pub fn type_id(&self) -> TypeId` [src]

Gets the `TypeId` of `self`. Read more

### `impl<T> Borrow<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow(&self) -> &T` [src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow_mut(&mut self) -> &mut T` [src]

Mutably borrows from an owned value. Read more

### `impl<T> From<T> for T` [src]

#### `pub fn from(t: T) -> T` [src]

Performs the conversion.

### `impl<T, U> Into<U> for T where
U: From<T>,` [src]

#### `pub fn into(self) -> U` [src]

Performs the conversion.

### `impl<T> ToOwned for T where
T: Clone,` [src]

#### `type Owned = T`

The resulting type after obtaining ownership.

#### `pub fn to_owned(&self) -> T` [src]

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

#### `pub fn clone_into(&self, target: &mut T)` [src]

🔬 This is a nightly-only experimental API. (`toowned_clone_into`)

recently added

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

### `impl<T, U> TryFrom<U> for T where
U: Into<T>,` [src]

#### `type Error = Infallible`

The type returned in the event of a conversion error.

#### `pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>` [src]

Performs the conversion.

### `impl<T, U> TryInto<U> for T where
U: TryFrom<T>,` [src]

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

The type returned in the event of a conversion error.

#### `pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>` [src]

Performs the conversion.