Skip to main content

Oneshot

Trait Oneshot 

Source
pub trait Oneshot:
    Send
    + Sync
    + Unpin
    + Future<Output = ()> {
    // Required methods
    fn new(timeout: Duration) -> Self;
    fn is_ticking(&self) -> bool;
    fn is_expired(&self) -> bool;
    fn cancel(&mut self);
    fn restart(&mut self, timeout: Duration, waker: &Waker);
}
Expand description

One-shot timer that expires once

Trait itself describes Future that resolves after timeout

Most common platforms are supplied via alias Timer

§Common implementations:

  • Windows uses thread pooled timer
  • Apple systems uses dispatch source API
  • Posix compatible timer_create, available on major Posix-compliant systems. Depends on availability of siginfo_t::si_value method.
  • Wasm uses Web API SetTimeout
  • Dummy timer is used when no implementation is available. Panics when used.

§Feature tokio_on

  • Linux uses timerfd_create, replaces Posix tiemr when enabled.
  • Other unix systems uses kqueue, replaces Apple timer when enabled.
 use async_timer::oneshot::{Oneshot, Timer};

 use std::time;

 async fn do_stuff() {
     let work = Timer::new(time::Duration::from_secs(2));

     let before = time::SystemTime::now();
     work.await;
     let after = time::SystemTime::now();
     let diff = after.duration_since(before).unwrap();

     assert_eq!(diff.as_secs(), 2);
 }

Required Methods§

Source

fn new(timeout: Duration) -> Self

Creates new instance without actually starting timer.

Timer should start only on first Future::poll

Source

fn is_ticking(&self) -> bool

Returns whether timer is ongoing.

Note that if it returns false it doesn’t mean that is_expired will return true as initially timer is not armed.

Source

fn is_expired(&self) -> bool

Returns whether timer has expired.

Source

fn cancel(&mut self)

Cancels ongoing timer, if it is not expired yet.

Source

fn restart(&mut self, timeout: Duration, waker: &Waker)

Restarts timer with new timeout value.

If timer is already running, then over-write old value and replaces waker.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§