Graceful Tokio Shutdown with Notify

Signal shutdown with Tokio Notify, let each worker finish its current cycle, and join every task before the process exits.

RustResilience

Code

rustsnippet
38 lines
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use tokio::task::JoinSet;
use tokio::time::sleep;

#[tokio::main]
async fn main() {
    let shutdown = Arc::new(Notify::new());
    let mut tasks = JoinSet::new();

    for worker in 0..3 {
        let shutdown = Arc::clone(&shutdown);
        tasks.spawn(async move {
            loop {
                tokio::select! {
                    _ = shutdown.notified() => {
                        println!("worker {worker} draining");
                        break;
                    }
                    _ = sleep(Duration::from_millis(25)) => {
                        println!("worker {worker} tick");
                    }
                }
            }
            sleep(Duration::from_millis(20)).await;
            println!("worker {worker} stopped");
        });
    }

    sleep(Duration::from_millis(60)).await;
    shutdown.notify_waiters();
    while let Some(result) = tasks.join_next().await {
        result.expect("worker panicked");
    }
    println!("shutdown complete");
}

How it works

Graceful Tokio Shutdown with Notify is built around the function main.

Repetition is confined to for worker in 0..3 — the rest of the file is straight-line.

What to watch for

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

Applying it

Running the file prints labeled results such as worker, shutdown complete — each operation’s effect is visible in the output.

Statements that matter

while let Some(result) = tasks.join_next().await {
result.expect("worker panicked");
}
_ = sleep(Duration::from_millis(25)) => {
println!("worker {worker} tick");
}
_ = shutdown.notified() => {
println!("worker {worker} draining");
break;
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `tokio::sync::Notify`, `tokio::task::JoinSet` and `tokio::time::sleep` must be present in the project or the import fails at load time.