Rust

Async Timeout

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap any future in `tokio::time::timeout` to fail it if it takes too long. Returns `Err(Elapsed)` on timeout; you decide what to do next (retry, fall back, propagate).
Rust
Raw
use tokio::time::{sleep, timeout, Duration};

async fn slow() -> i32 {
    sleep(Duration::from_secs(5)).await;
    42
}

#[tokio::main]
async fn main() {
    match timeout(Duration::from_secs(2), slow()).await {
        Ok(value)  => println!("got {value}"),
        Err(_)     => println!("timed out"),
    }

    // Composed with ? — works because timeout returns Result
    let result: Result<i32, _> = timeout(Duration::from_millis(100), async { 7 }).await;
    println!("{:?}", result);                         // Ok(7)
}
Tags

Save your own code snippets

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