Function maitake::time::timeout

source ·
pub fn timeout<F: Future>(duration: Duration, future: F) -> Timeout<'static, F> 
Expand description

Requires the provided Future to complete before the specified Duration has elapsed.

This function uses the global default timer, and the returned Timeout future will live for the 'static lifetime. See the module-level documentation for details on using the global default timer.

Output

  • Ok(F::Output) if the inner future completed before the specified timeout.
  • Err(Elapsed) if the timeout elapsed before the inner Future completed.

Cancellation

Dropping a Timeout future cancels the timeout. The wrapped Future can be extracted from the Timeout future by calling Timeout::into_inner, allowing the future to be polled without failing if the timeout elapses.

Panics

For a version of this function that does not panic, use the try_timeout() function instead.

Examples

use maitake::time::{timeout, Duration};

/// A function that might wait for a long time before it completes.
async fn do_slow_stuff() {
   // do some slow stuff ...
}

async fn example() {
    // try to do some slow stuff, but if it takes longer than 10 seconds,
    // give up.
    match timeout(Duration::from_secs(10), do_slow_stuff()).await {
        Ok(_) => println!("slow stuff completed successfully"),
        Err(elapsed) =>
            eprintln!("slow stuff did not complete in {:?}!", elapsed.duration()),
    }
}