Use tokio::task::spawn to run async functions concurrently and get a JoinHandle to await their results.
Use tokio::task::spawn to run an async function concurrently on the Tokio runtime, returning a JoinHandle to track its completion.
use tokio::task::spawn;
#[tokio::main]
async fn main() {
let handle = spawn(async {
println!("Running in a spawned task");
});
handle.await.unwrap();
}
Ensure your Cargo.toml includes tokio with the rt-multi-thread feature enabled.
Tokio spawn lets you start a background task that runs alongside your main program without blocking it. Think of it like handing a task to a worker so you can keep working on other things while they finish theirs. You use it when you need to perform multiple operations at once, like downloading files or processing data, without waiting for each one to finish before starting the next.