Tokio Timeout With select!
Race an async operation against a timer using tokio select!, so a slow future is abandoned cleanly when the deadline fires first.
Code
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn fetch_remote() -> String {
sleep(Duration::from_millis(200)).await;
String::from("payload")
}
#[tokio::main]
async fn main() {
match timeout(Duration::from_millis(50), fetch_remote()).await {
Ok(body) => println!("received {body}"),
Err(_) => println!("request timed out"),
}
tokio::select! {
result = fetch_remote() => println!("first: {result}"),
_ = sleep(Duration::from_millis(100)) => println!("deadline hit first"),
}
}How it works
Tokio Timeout With select! comes down to the functions fetch_remote and main.
The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
What to watch for
- Plan for an install step:
tokio::time::is a real dependency, resolved by the package manager.
Putting it to use
The main signature reads fn fetch_remote() -> String
The demo output is labeled (received, request timed out, first:), so every printed line maps back to its originating operation.
There are 1 call inside main — fetch_remote — executed top to bottom.
Core lines
match timeout(Duration::from_millis(50), fetch_remote()).await {
Ok(body) => println!("received {body}"),
Err(_) => println!("request timed out"),
}
async fn fetch_remote() -> String {
sleep(Duration::from_millis(200)).await;
String::from("payload")
}
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- `tokio::time::` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.