#tokio #timeout #async

async-timeouts

An instrument to start async tasks after timeouts

5 unstable releases

new 0.3.2 Apr 16, 2025
0.3.1 Apr 16, 2025
0.2.2 Apr 15, 2025
0.1.1 Apr 8, 2025

#457 in Asynchronous

Download history 61/week @ 2025-04-03 355/week @ 2025-04-10

420 downloads per month

MIT license

14KB
97 lines

Async Timeouts Helper

It is a simple instrument to delay execution of an async task with additional methods:

  • reset timeout with a new value, i.e. to delay execution of your task;
  • restart timeout with a new or previous task;
  • stop the timer before your task will be executed;
  • finished — check if the timer of the task is over or not.

It is convinient to use this crate with Notify or different channels (i.e. async_channel).

Examples

Basic 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 timer = Instant::now();
    {
        let event = event.clone();
        // Let's notify our event after 3 seconds
        Timeout::set(Duration::from_secs(3), async move {
            event.notify_one();
        }).await;
    }
    event.notified().await;
    assert!(timer.elapsed().as_secs() >= 3);
    println!("{} seconds elapsed", timer.elapsed().as_secs());
}

If you do not need to start timer when Timeout is created, use Timeout::default() with a subsequent call to the restart method

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

#[tokio::main]
async fn main() {
    let mut task = Timeout::default();
    println!("Task timer is not running yet: {}", task.finished());
    assert!(task.finished());

    task.restart(Duration::from_secs(3), async move {
        // Some task here
        tokio::time::sleep(Duration::from_secs(1)).await;
    }).await;
    println!("Task timer is running: {}", !task.finished());
    assert!(!task.finished());

    task.stop().await;
    println!("Task timer is stoped: {}", task.finished());
    assert!(task.finished());
}

Take a look at more complex examples:

Dependencies

~3.5–9MB
~72K SLoC