Cancellation Token Budget
Share a child cancellation token with each worker and cancel the whole batch when the execution budget runs out.
Code
use std::time::Duration;
use tokio::time::sleep;
use tokio_util::sync::CancellationToken;
async fn worker(id: u32, token: CancellationToken) {
tokio::select! {
_ = token.cancelled() => {
println!("worker {id} cancelled");
}
_ = sleep(Duration::from_millis(40 * id as u64)) => {
println!("worker {id} finished");
}
}
}
async fn run_with_budget(budget: Duration) -> u32 {
let token = CancellationToken::new();
let mut handles = Vec::new();
for id in 1..=4 {
let child = token.child_token();
handles.push(tokio::spawn(worker(id, child)));
}
let timer = {
let token = token.clone();
tokio::spawn(async move {
sleep(budget).await;
token.cancel();
})
};
let mut returned = 0;
for handle in handles {
if handle.await.is_ok() {
returned += 1;
}
}
let _ = timer.await;
returned
}
#[tokio::main]
async fn main() {
let returned = run_with_budget(Duration::from_millis(100)).await;
println!("workers returned: {returned}");
}How it works
Cancellation Token Budget keeps everything in the functions worker, run_with_budget and main.
Repetition is confined to for id in 1..=4 — the rest of the file is straight-line.
What to watch for
- Plan for an install step:
tokio::time::sleepandtokio_util::sync::CancellationTokenare a real dependency, resolved by the package manager.
Putting it to use
The primary signature is fn worker(id: u32, token: CancellationToken)
The run prints worker, workers returned: — each prefix names the step that produced it.
Running the file executes main, which drives run_with_budget in order.
Core lines
_ = sleep(Duration::from_millis(40 * id as u64)) => {
println!("worker {id} finished");
}
_ = token.cancelled() => {
println!("worker {id} cancelled");
}
tokio::spawn(async move {
sleep(budget).await;
token.cancel();
})
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
- Does this require external packages?
- Yes — `tokio::time::sleep` and `tokio_util::sync::CancellationToken`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.