async_exec/
time.rs

1//! Future Timing Utilities
2
3use std::future::Future;
4use std::time::{Duration, Instant};
5
6use async_io::Timer;
7use futures_lite::future::or;
8
9/// This trait adds a `timeout` method to all futures.
10pub trait FutureTimeout<T>: Future<Output = T> + Sized {
11    /// This method, implemented for all futures, returns another future which
12    /// yields None if the inner future takes too long to yield its output.
13    ///
14    /// If the inner future yields in time, its output is in turn yielded in `Some(_)`.
15    fn timeout(self, duration: Duration) -> impl Future<Output = Option<T>> {
16        let this = async { Some(self.await) };
17
18        let timeout = async move {
19            sleep(duration).await;
20            None
21        };
22
23        or(this, timeout)
24    }
25}
26
27impl<T, F: Future<Output = T>> FutureTimeout<T> for F {}
28
29/// Pauses the current task for some time.
30pub async fn sleep(duration: Duration) {
31    Timer::after(duration).await;
32}
33
34/// Pauses the current task until an expiration instant.
35pub async fn sleep_until(instant: Instant) {
36    Timer::at(instant).await;
37}