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();
}
};
let mut delayed_task = Timeout::set(Duration::from_secs(2), task1).await;
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");
}
tokio::select! {
Ok(_) = task_1_rx.recv() => println!("It must be 2 seconds now after the start: {} seconds", timer.elapsed().as_secs()),
Ok(_) = task_2_rx.recv() => println!("It must be 4 seconds now after the start: {} seconds", timer.elapsed().as_secs()),
}
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()
);
}