Rust

tokio::spawn — Independent Tasks

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`spawn` runs a future on the runtime as an independent task — fire-and-forget, or `.await` the returned `JoinHandle` to get its result. Equivalent to threads but multiplexed onto the worker pool.
Rust
Raw
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // Fire-and-forget
    tokio::spawn(async {
        sleep(Duration::from_millis(50)).await;
        println!("background task done");
    });

    // Spawn and collect results
    let handles: Vec<_> = (0..5).map(|i| {
        tokio::spawn(async move {
            sleep(Duration::from_millis(100)).await;
            i * 10
        })
    }).collect();

    for h in handles {
        println!("got {}", h.await.unwrap());
    }

    sleep(Duration::from_millis(100)).await;     // give the fire-and-forget time to finish
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.