Gracefully shutdown async tasks in Tokio by awaiting their JoinHandles or using tokio::select! to cancel them on a shutdown signal.
use tokio::task::JoinHandle;
async fn my_task() {
// Task logic here
}
#[tokio::main]
async fn main() {
let handle: JoinHandle<()> = tokio::spawn(my_task());
// Wait for the task to finish gracefully
handle.await.expect("Task panicked");
}
For immediate cancellation on a signal (like Ctrl+C), use tokio::select! to race the task against the shutdown event, which drops the task if the signal arrives first.