maitake::time

Function try_timeout

Source
pub fn try_timeout<F: Future>(
    duration: Duration,
    future: F,
) -> Result<Timeout<'static, F>, TimerError>
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.

§Returns

§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

This function does not panic. For a version of this function that panics rather than returning a TimerError, use timeout() instead.

§Examples

use maitake::time::{self, 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() {
    // if we can't create the timeout, just wait for the future to complete
    // with no timeout.
    match time::try_timeout(Duration::from_secs(10), do_slow_stuff()) {
        // we successfully created a timeout, so await the timeout future.
        Ok(timeout) => match timeout.await {
            Ok(_) => {},
            Err(elapsed) => {
                eprintln!("slow stuff did not complete in {:?}", elapsed.duration());
                return;
            },
        },
        // a timeout could not be created, so just try the slow stuff
        // without setting the timeout.
        Err(_) => do_slow_stuff().await,
    };

    println!("slow stuff completed successfully");
}