The tokio::select! macro runs multiple futures concurrently and executes the code block for whichever one finishes first.
Use the tokio::select! macro to run multiple futures concurrently and execute the block corresponding to the one that completes first.
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
tokio::select! {
_ = sleep(Duration::from_secs(1)) => println!("One second passed"),
_ = sleep(Duration::from_secs(2)) => println!("Two seconds passed"),
}
}
The tokio select macro lets you run several tasks at the same time and immediately handles the one that finishes first. It is like having two timers running; when the first one goes off, you stop the other one and deal with the result. You use this when you need to race against a timeout or handle whichever network request returns fastest.