Function interval_future::to_future [−][src]
pub async fn to_future<O, F>(f: F, interval_period: Duration) -> O where
F: FnMut() -> Poll<O> + Unpin,
Creates a new future which wraps a synchronous function f
that may be called repeatedly on interval_period
until
it completes.
Generally, when using futures, an explicit waker should be used to cause re-polling on a more precise basis, but that isn’t always available. This method allows callers to create a future which will automatically be-checked with a specified regularity.
Arguments
f
: A function to be polled. ReturnsPoll::Ready
with a result to complete the future, andPoll::Pending
otherwise.f
will not be re-invoked after completing.interval_period
: A duration of time to wait before re-invokingf
. This is a suggestion, as the function may actually be re-polled more frequently.
Example
use std::task::Poll; use std::time::{Duration, Instant}; #[tokio::main] async fn main() { let time_to_complete = Duration::from_secs(1); let interval = Duration::from_millis(200); let timeout = Duration::from_secs(2); let poll_start = Instant::now(); let f = || { let elapsed = Instant::now().duration_since(poll_start); if elapsed > time_to_complete { println!("Ready"); Poll::Ready(5) } else { println!("Not ready after {} ms", elapsed.as_millis()); Poll::Pending } }; let fut = interval_future::to_future(f, interval); let val = tokio::time::timeout(timeout, fut).await.unwrap(); println!("Got my value: {}", val); }