pub enum OneshotTimer {
    Scheduled(Instant),
    Expired,
}
Expand description

OneshotTimer expires once after a given duration

OneshotTimer is used for tasks that need to be executed once after some delay. OneshotTimer is an extension and built on top of tokio::time::Sleep. In OneshotTimer::Scheduled state it will expire once and transition into OneshotTimer::Expired state.

use async_timers::OneshotTimer;
use tokio::time::{Duration, timeout};

#[tokio::main]
async fn main() {
    let mut timer = OneshotTimer::scheduled(Duration::from_millis(10));

    timer.tick().await;

    // approximately 10ms have elapsed.

    let result = timeout(Duration::from_millis(100), timer.tick()).await;
    assert!(result.is_err(), "Timeout should occur since timer is expired");

    timer.schedule(Duration::from_millis(30));

    let result = timeout(Duration::from_millis(100), timer.tick()).await;
    assert!(result.is_ok(), "Timeout should not occur since timer has been scheduled");
}

Variants

Scheduled(Instant)

Expired

Implementations

Create a timer scheduled to be expired after duration

Create a timer that won’t expire

Schedule a new duration

Cancel the timer

Returns a Future that will expire based on timer’s state

Trait Implementations

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.