How to Cancel Async Tasks in Rust

Drop the JoinHandle returned by tokio::task::spawn to immediately cancel the async task.

Cancel an async task in Rust by dropping its JoinHandle returned from tokio::task::spawn. When the handle is dropped, the task is immediately aborted and its resources are cleaned up.

use tokio::task::spawn;

#[tokio::main]
async fn main() {
    let handle = spawn(async {
        loop {
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            println!("Still running");
        }
    });

    // Cancel the task by dropping the handle
    drop(handle);
}