Use tokio::select! to run multiple async operations concurrently and handle the one that completes first.
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let mut interval = tokio::time::interval(Duration::from_secs(1));
let mut timeout = tokio::time::sleep(Duration::from_secs(5));
tokio::select! {
_ = interval.tick() => println!("Interval ticked"),
_ = timeout => println!("Timeout reached"),
}
}
This macro cancels all other branches once one completes, preventing resource leaks.