Tokio Cancellation Token Graceful
Use tokio cancellation tokens for graceful async task shutdown in Rust.
Code
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::CancellationTokenandtokio::time::sleepare 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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
FAQ
- Are there third-party dependencies?
- `tokio_util::sync::CancellationToken` and `tokio::time::sleep` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.