async_io

Struct Timer

Source
pub struct Timer { /* private fields */ }
Expand description

A future or stream that emits timed events.

Timers are futures that output a single Instant when they fire.

Timers are also streams that can output Instants periodically.

§Precision

There is a limit on the maximum precision that a Timer can provide. This limit is dependent on the current platform; for instance, on Windows, the maximum precision is about 16 milliseconds. Because of this limit, the timer may sleep for longer than the requested duration. It will never sleep for less.

§Examples

Sleep for 1 second:

use async_io::Timer;
use std::time::Duration;

Timer::after(Duration::from_secs(1)).await;

Timeout after 1 second:

use async_io::Timer;
use futures_lite::FutureExt;
use std::time::Duration;

let addrs = async_net::resolve("google.com:80")
    .or(async {
        Timer::after(Duration::from_secs(1)).await;
        Err(std::io::ErrorKind::TimedOut.into())
    })
    .await?;

Implementations§

Source§

impl Timer

Source

pub fn never() -> Timer

Creates a timer that will never fire.

§Examples

This function may also be useful for creating a function with an optional timeout.

use async_io::Timer;
use futures_lite::prelude::*;
use std::time::Duration;

async fn run_with_timeout(timeout: Option<Duration>) {
    let timer = timeout
        .map(|timeout| Timer::after(timeout))
        .unwrap_or_else(Timer::never);

    run_lengthy_operation().or(timer).await;
}

// Times out after 5 seconds.
run_with_timeout(Some(Duration::from_secs(5))).await;
// Does not time out.
run_with_timeout(None).await;
Source

pub fn after(duration: Duration) -> Timer

Creates a timer that emits an event once after the given duration of time.

§Examples
use async_io::Timer;
use std::time::Duration;

Timer::after(Duration::from_secs(1)).await;
Source

pub fn at(instant: Instant) -> Timer

Creates a timer that emits an event once at the given time instant.

§Examples
use async_io::Timer;
use std::time::{Duration, Instant};

let now = Instant::now();
let when = now + Duration::from_secs(1);
Timer::at(when).await;
Source

pub fn interval(period: Duration) -> Timer

Creates a timer that emits events periodically.

§Examples
use async_io::Timer;
use futures_lite::StreamExt;
use std::time::{Duration, Instant};

let period = Duration::from_secs(1);
Timer::interval(period).next().await;
Source

pub fn interval_at(start: Instant, period: Duration) -> Timer

Creates a timer that emits events periodically, starting at start.

§Examples
use async_io::Timer;
use futures_lite::StreamExt;
use std::time::{Duration, Instant};

let start = Instant::now();
let period = Duration::from_secs(1);
Timer::interval_at(start, period).next().await;
Source

pub fn will_fire(&self) -> bool

Indicates whether or not this timer will ever fire.

never() will never fire, and timers created with after() or at() will fire if the duration is not too large.

§Examples
use async_io::Timer;
use futures_lite::prelude::*;
use std::time::Duration;

// `never` will never fire.
assert!(!Timer::never().will_fire());

// `after` will fire if the duration is not too large.
assert!(Timer::after(Duration::from_secs(1)).will_fire());
assert!(!Timer::after(Duration::MAX).will_fire());

// However, once an `after` timer has fired, it will never fire again.
let mut t = Timer::after(Duration::from_secs(1));
assert!(t.will_fire());
(&mut t).await;
assert!(!t.will_fire());

// Interval timers will fire periodically.
let mut t = Timer::interval(Duration::from_secs(1));
assert!(t.will_fire());
t.next().await;
assert!(t.will_fire());
Source

pub fn set_after(&mut self, duration: Duration)

Sets the timer to emit an event once after the given duration of time.

Note that resetting a timer is different from creating a new timer because set_after() does not remove the waker associated with the task that is polling the timer.

§Examples
use async_io::Timer;
use std::time::Duration;

let mut t = Timer::after(Duration::from_secs(1));
t.set_after(Duration::from_millis(100));
Source

pub fn set_at(&mut self, instant: Instant)

Sets the timer to emit an event once at the given time instant.

Note that resetting a timer is different from creating a new timer because set_at() does not remove the waker associated with the task that is polling the timer.

§Examples
use async_io::Timer;
use std::time::{Duration, Instant};

let mut t = Timer::after(Duration::from_secs(1));

let now = Instant::now();
let when = now + Duration::from_secs(1);
t.set_at(when);
Source

pub fn set_interval(&mut self, period: Duration)

Sets the timer to emit events periodically.

Note that resetting a timer is different from creating a new timer because set_interval() does not remove the waker associated with the task that is polling the timer.

§Examples
use async_io::Timer;
use futures_lite::StreamExt;
use std::time::{Duration, Instant};

let mut t = Timer::after(Duration::from_secs(1));

let period = Duration::from_secs(2);
t.set_interval(period);
Source

pub fn set_interval_at(&mut self, start: Instant, period: Duration)

Sets the timer to emit events periodically, starting at start.

Note that resetting a timer is different from creating a new timer because set_interval_at() does not remove the waker associated with the task that is polling the timer.

§Examples
use async_io::Timer;
use futures_lite::StreamExt;
use std::time::{Duration, Instant};

let mut t = Timer::after(Duration::from_secs(1));

let start = Instant::now();
let period = Duration::from_secs(2);
t.set_interval_at(start, period);

Trait Implementations§

Source§

impl Debug for Timer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Timer

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Future for Timer

Source§

type Output = Instant

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more
Source§

impl Stream for Timer

Source§

type Item = Instant

Values yielded by the stream.
Source§

fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>>

Attempt to pull out the next value of this stream, registering the current task for wakeup if the value is not yet available, and returning None if the stream is exhausted. Read more
Source§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more

Auto Trait Implementations§

§

impl Freeze for Timer

§

impl RefUnwindSafe for Timer

§

impl Send for Timer

§

impl Sync for Timer

§

impl Unpin for Timer

§

impl UnwindSafe for Timer

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<F> FutureExt for F
where F: Future + ?Sized,

Source§

fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where Self: Unpin,

A convenience for calling Future::poll() on !Unpin types.
Source§

fn or<F>(self, other: F) -> Or<Self, F>
where Self: Sized, F: Future<Output = Self::Output>,

Returns the result of self or other future, preferring self if both are ready. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<F> IntoFuture for F
where F: Future,

Source§

type Output = <F as Future>::Output

The output that the future will produce on completion.
Source§

type IntoFuture = F

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
Source§

impl<S> StreamExt for S
where S: Stream + ?Sized,

Source§

fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
where Self: Unpin,

A convenience for calling Stream::poll_next() on !Unpin types.
Source§

fn next(&mut self) -> NextFuture<'_, Self>
where Self: Unpin,

Retrieves the next item in the stream. Read more
Source§

fn try_next<T, E>(&mut self) -> TryNextFuture<'_, Self>
where Self: Stream<Item = Result<T, E>> + Unpin,

Retrieves the next item in the stream. Read more
Source§

fn count(self) -> CountFuture<Self>
where Self: Sized,

Counts the number of items in the stream. Read more
Source§

fn map<T, F>(self, f: F) -> Map<Self, F>
where Self: Sized, F: FnMut(Self::Item) -> T,

Maps items of the stream to new values using a closure. Read more
Source§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where Self: Sized, U: Stream, F: FnMut(Self::Item) -> U,

Maps items to streams and then concatenates them. Read more
Source§

fn flatten(self) -> Flatten<Self>
where Self: Sized, Self::Item: Stream,

Concatenates inner streams. Read more
Source§

fn then<F, Fut>(self, f: F) -> Then<Self, F, Fut>
where Self: Sized, F: FnMut(Self::Item) -> Fut, Fut: Future,

Maps items of the stream to new values using an async closure. Read more
Source§

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where Self: Sized, P: FnMut(&Self::Item) -> bool,

Keeps items of the stream for which predicate returns true. Read more
Source§

fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
where Self: Sized, F: FnMut(Self::Item) -> Option<T>,

Filters and maps items of the stream using a closure. Read more
Source§

fn take(self, n: usize) -> Take<Self>
where Self: Sized,

Takes only the first n items of the stream. Read more
Source§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where Self: Sized, P: FnMut(&Self::Item) -> bool,

Takes items while predicate returns true. Read more
Source§

fn skip(self, n: usize) -> Skip<Self>
where Self: Sized,

Skips the first n items of the stream. Read more
Source§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where Self: Sized, P: FnMut(&Self::Item) -> bool,

Skips items while predicate returns true. Read more
Source§

fn step_by(self, step: usize) -> StepBy<Self>
where Self: Sized,

Yields every stepth item. Read more
Source§

fn chain<U>(self, other: U) -> Chain<Self, U>
where Self: Sized, U: Stream<Item = Self::Item>,

Appends another stream to the end of this one. Read more
Source§

fn cloned<'a, T>(self) -> Cloned<Self>
where Self: Sized + Stream<Item = &'a T>, T: Clone + 'a,

Clones all items. Read more
Source§

fn copied<'a, T>(self) -> Copied<Self>
where Self: Sized + Stream<Item = &'a T>, T: Copy + 'a,

Copies all items. Read more
Source§

fn collect<C>(self) -> CollectFuture<Self, C>
where Self: Sized, C: Default + Extend<Self::Item>,

Collects all items in the stream into a collection. Read more
Source§

fn try_collect<T, E, C>(self) -> TryCollectFuture<Self, C>
where Self: Sized + Stream<Item = Result<T, E>>, C: Default + Extend<T>,

Collects all items in the fallible stream into a collection. Read more
Source§

fn partition<B, P>(self, predicate: P) -> PartitionFuture<Self, P, B>
where Self: Sized, B: Default + Extend<Self::Item>, P: FnMut(&Self::Item) -> bool,

Partitions items into those for which predicate is true and those for which it is false, and then collects them into two collections. Read more
Source§

fn fold<T, F>(self, init: T, f: F) -> FoldFuture<Self, F, T>
where Self: Sized, F: FnMut(T, Self::Item) -> T,

Accumulates a computation over the stream. Read more
Source§

fn try_fold<T, E, F, B>( &mut self, init: B, f: F, ) -> TryFoldFuture<'_, Self, F, B>
where Self: Sized + Stream<Item = Result<T, E>> + Unpin, F: FnMut(B, T) -> Result<B, E>,

Accumulates a fallible computation over the stream. Read more
Source§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,

Maps items of the stream to new values using a state value and a closure. Read more
Source§

fn fuse(self) -> Fuse<Self>
where Self: Sized,

Fuses the stream so that it stops yielding items after the first None. Read more
Source§

fn cycle(self) -> Cycle<Self>
where Self: Sized + Clone,

Repeats the stream from beginning to end, forever. Read more
Source§

fn enumerate(self) -> Enumerate<Self>
where Self: Sized,

Enumerates items, mapping them to (index, item). Read more
Source§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where Self: Sized, F: FnMut(&Self::Item),

Calls a closure on each item and passes it on. Read more
Source§

fn nth(&mut self, n: usize) -> NthFuture<'_, Self>
where Self: Unpin,

Gets the nth item of the stream. Read more
Source§

fn last(self) -> LastFuture<Self>
where Self: Sized,

Returns the last item in the stream. Read more
Source§

fn find<P>(&mut self, predicate: P) -> FindFuture<'_, Self, P>
where Self: Unpin, P: FnMut(&Self::Item) -> bool,

Finds the first item of the stream for which predicate returns true. Read more
Source§

fn find_map<F, B>(&mut self, f: F) -> FindMapFuture<'_, Self, F>
where Self: Unpin, F: FnMut(Self::Item) -> Option<B>,

Applies a closure to items in the stream and returns the first Some result. Read more
Source§

fn position<P>(&mut self, predicate: P) -> PositionFuture<'_, Self, P>
where Self: Unpin, P: FnMut(Self::Item) -> bool,

Finds the index of the first item of the stream for which predicate returns true. Read more
Source§

fn all<P>(&mut self, predicate: P) -> AllFuture<'_, Self, P>
where Self: Unpin, P: FnMut(Self::Item) -> bool,

Tests if predicate returns true for all items in the stream. Read more
Source§

fn any<P>(&mut self, predicate: P) -> AnyFuture<'_, Self, P>
where Self: Unpin, P: FnMut(Self::Item) -> bool,

Tests if predicate returns true for any item in the stream. Read more
Source§

fn for_each<F>(self, f: F) -> ForEachFuture<Self, F>
where Self: Sized, F: FnMut(Self::Item),

Calls a closure on each item of the stream. Read more
Source§

fn try_for_each<F, E>(&mut self, f: F) -> TryForEachFuture<'_, Self, F>
where Self: Unpin, F: FnMut(Self::Item) -> Result<(), E>,

Calls a fallible closure on each item of the stream, stopping on first error. Read more
Source§

fn zip<U>(self, other: U) -> Zip<Self, U>
where Self: Sized, U: Stream,

Zips up two streams into a single stream of pairs. Read more
Source§

fn unzip<A, B, FromA, FromB>(self) -> UnzipFuture<Self, FromA, FromB>
where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Stream<Item = (A, B)>,

Collects a stream of pairs into a pair of collections. Read more
Source§

fn or<S>(self, other: S) -> Or<Self, S>
where Self: Sized, S: Stream<Item = Self::Item>,

Merges with other stream, preferring items from self whenever both streams are ready. Read more
Source§

fn drain(&mut self) -> Drain<'_, Self>

Yields all immediately available values from a stream. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more