Tokio Cancellation Token Graceful

Use tokio cancellation tokens for graceful async task shutdown in Rust.

RustResilience

Code

rustsnippet
26 lines
use tokio_util::sync::CancellationToken;
use tokio::time::sleep;
use std::time::Duration;

async fn worker(token: CancellationToken, id: usize) {
    loop {
        tokio::select! {
            _ = token.cancelled() => {
                println!("worker {} cancelled", id);
                return;
            }
            _ = sleep(Duration::from_millis(100)) => {
                println!("worker {} tick", id);
            }
        }
    }
}

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    for i in 0..3 { tokio::spawn(worker(token.clone(), i)); }
    sleep(Duration::from_secs(1)).await;
    token.cancel();
    sleep(Duration::from_secs(1)).await;
}

Inside the snippet

Tokio Cancellation Token Graceful keeps everything in the functions worker and main.

Iteration happens inside for i in 0..3 { tokio::spawn(worker(token.clone(), i)); } — everything outside it runs once.

What to watch for

  • Plan for an install step: tokio_util::sync::CancellationToken and tokio::time::sleep are a real dependency, resolved by the package manager.

Using it

Signature: fn worker(token: CancellationToken, id: usize)

The demo output is labeled (worker), so every printed line maps back to its originating operation.

Start the program and main runs worker one after another.

Key statements

_ = sleep(Duration::from_millis(100)) => {
println!("worker {} tick", id);
}
_ = token.cancelled() => {
println!("worker {} cancelled", id);
return;
}
async fn main() {
let token = CancellationToken::new();
for i in 0..3 { tokio::spawn(worker(token.clone(), i)); }
sleep(Duration::from_secs(1)).await;
token.cancel();
sleep(Duration::from_secs(1)).await;
}

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`tokio_util::sync::CancellationToken` and `tokio::time::sleep` — install them with the package manager before running.