use std::time::Duration;
use tokio_task_supervisor::TaskSupervisor;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let supervisor = TaskSupervisor::new();
let worker = supervisor.spawn_with_token(|token| async move {
let mut ticks = 0u32;
loop {
tokio::select! {
_ = token.cancelled() => {
println!("worker: stopping after {ticks} ticks");
break;
}
_ = tokio::time::sleep(Duration::from_millis(300)) => {
ticks += 1;
if ticks % 5 == 0 {
println!("worker: still alive (ticks = {ticks})");
}
}
}
}
ticks
});
println!("main: let the worker spin for a while");
tokio::time::sleep(Duration::from_secs(2)).await;
println!("main: triggering cooperative shutdown");
supervisor.cancel();
let ticks = worker.await.expect("worker task panicked");
println!("main: worker observed cancellation after {ticks} ticks");
supervisor.shutdown().await;
println!("main: shutdown finished");
}