Tokio Cancellation Token Graceful

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

RustResilience

Code

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