async-timeouts 0.3.2

An instrument to start async tasks after timeouts
Documentation
use std::time::{Duration, Instant};

use async_channel::unbounded;
use async_timeouts::Timeout;

#[tokio::main(flavor = "current_thread")]
async fn main() {
    println!("Start!");
    let timer = Instant::now();
    let (task_1_tx, task_1_rx) = unbounded::<u64>();
    let (task_2_tx, task_2_rx) = unbounded::<u64>();
    let (task_3_tx, task_3_rx) = unbounded::<u64>();

    let task1 = {
        async move {
            task_1_tx.send(2).await.unwrap();
        }
    };

    let task2 = {
        async move {
            task_2_tx.send(4).await.unwrap();
        }
    };

    let task3 = {
        async move {
            task_3_tx.send(3).await.unwrap();
        }
    };

    // Timeout should be expired in 2 seconds and to start our task
    let mut delayed_task = Timeout::set(Duration::from_secs(2), task1).await;

    // Here let's restart timeout with the new task and 4 seconds to expire
    delayed_task.restart(Duration::from_secs(4), task2).await;

    if let Err(_) = task_1_rx.try_recv() {
        println!("Here we receive an err, because task 1 was droped ahead of time after the `restart` method");
    }

    // We are waiting here `Ok` message, because `task_1_rx` will receive an `Err` message after the task 1 was droped.
    tokio::select! {
        // The first task has been already droped and we never will receive this message
        Ok(_) = task_1_rx.recv() => println!("It must be 2 seconds now after the start: {} seconds", timer.elapsed().as_secs()),
        // We expect to receive this message after `Timeout` timer expires
        Ok(_) = task_2_rx.recv() => println!("It must be 4 seconds now after the start: {} seconds", timer.elapsed().as_secs()),
    }

    // Let's reuse out `Timeout` with the task 3
    delayed_task.restart(Duration::from_secs(2), task3).await;

    println!(
        "It must be 3 seconds now after the delayed_task was restarted: {} seconds",
        task_3_rx.recv().await.unwrap()
    );
}