Timeout

Struct Timeout 

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

See more information about reset, restart, stop and finished methods

Implementations§

Source§

impl Timeout

Source

pub async fn set<T>( timeout: Duration, f: impl Future<Output = T> + Send + 'static, ) -> Self

Schedule the task inside closure after timeout

Source

pub async fn reset(&self, timeout: Duration) -> Result<()>

Reset timeout with a new value, i.e. to delay execution of your task. It will return an error, if the timeout timer is not running. For that cases use restart insteed.

§Example
use std::time::{Duration, Instant};
use async_timeouts::Timeout;
use tokio::sync::Notify;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let event = Arc::new(Notify::new());
    let event_cloned = event.clone();
    let delayed_task = Timeout::set(Duration::from_secs(3), async move {
        println!("This message will be printed after 6 seconds");
        event_cloned.notify_one();
    }).await;
    let _ = delayed_task.reset(Duration::from_secs(6)).await;
    event.notified().await;
}
Source

pub async fn restart<T>( &mut self, timeout: Duration, f: impl Future<Output = T> + Send + 'static, )

Restart timeout with a new or previous task. Timeout instance will be reused if the previous timer is over, or the previous task will be stoped ahead of time if not.

§Example
use std::time::{Duration, Instant};
use async_timeouts::Timeout;
use async_channel::unbounded;

#[tokio::main]
async fn main() {
    let timer = Instant::now();
    let (task_tx, task_rx) = unbounded::<i32>();
     
    let mut delayed_task = {
        let task_tx = task_tx.clone();
        Timeout::set(Duration::from_secs(3), async move {
            let _ = task_tx.send(1).await;
        }).await
    };
     
    delayed_task.restart(Duration::from_secs(6), async move {
        let _ = task_tx.send(2).await;
    }).await;
     
    if let Ok(msg) = task_rx.recv().await {
        println!("Task is finished {msg}");
    }
    assert!(timer.elapsed().as_secs() >= 6);
}
Source

pub async fn stop(&mut self)

Stop the timer before your task will be executed. The method will do nothig if you do not run timer inside Timeout by using Timeout::default().

§Example
use std::time::Duration;
use async_timeouts::Timeout;

#[tokio::main]
async fn main() {
    let mut delayed_task = Timeout::set(Duration::from_secs(3), async move {
        println!("This message will never be printed and event will never be notified.");
    }).await;
    assert!(!delayed_task.finished());
    delayed_task.stop().await;
    assert!(delayed_task.finished());
}
Source

pub fn finished(&self) -> bool

Check if the timer of the task is over or not.

§Example
use std::time::Duration;
use async_timeouts::Timeout;
use tokio::sync::Notify;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let event = Arc::new(Notify::new());
     
    let event_cloned = event.clone();
    let delayed_task = Timeout::set(Duration::from_secs(3), async move {
        event_cloned.notify_one();
    }).await;
     
    assert!(!delayed_task.finished());
    println!("delayed_task is not finished yet: {}", delayed_task.finished());
    event.notified().await;
    assert!(delayed_task.finished());
    println!("delayed_task is finished: {}", delayed_task.finished());
}

Trait Implementations§

Source§

impl Clone for Timeout

Source§

fn clone(&self) -> Timeout

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Timeout

Source§

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

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

impl Default for Timeout

Source§

fn default() -> Timeout

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

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.