async_timeouts/lib.rs
1// Copyright 2024 Artyom Sinyugin
2
3//! # Async Timeouts Helper
4//! It is a simple instrument to delay execution of an async task with additional methods:
5//! * [reset] timeout with a new value, i.e. to delay execution of your task;
6//! * [restart] timeout with a new or previous task;
7//! * [stop] the timer before your task will be executed;
8//! * [finished] — check if the timer of the task is over or not.
9//!
10//! It is convinient to use this crate with [Notify] or different
11//! channels (i.e. [async_channel]).
12//!
13//! ## Examples
14//! Basic example
15//! ```rust
16//! use std::time::{Duration, Instant};
17//! use async_timeouts::Timeout;
18//! use tokio::sync::Notify;
19//! use std::sync::Arc;
20//!
21//! #[tokio::main]
22//! async fn main() {
23//! let event = Arc::new(Notify::new());
24//! let timer = Instant::now();
25//! {
26//! let event = event.clone();
27//! // Let's notify our event after 3 seconds
28//! Timeout::set(Duration::from_secs(3), async move {
29//! event.notify_one();
30//! }).await;
31//! }
32//! event.notified().await;
33//! assert!(timer.elapsed().as_secs() >= 3);
34//! println!("{} seconds elapsed", timer.elapsed().as_secs());
35//! }
36//! ```
37//!
38//! If you do not need to start timer when `Timeout` is created, use `Timeout::default()` with
39//! a subsequent call to the [restart] method
40//! ```rust
41//! use std::time::Duration;
42//! use async_timeouts::Timeout;
43//!
44//! #[tokio::main]
45//! async fn main() {
46//! let mut task = Timeout::default();
47//! println!("Task timer is not running yet: {}", task.finished());
48//! assert!(task.finished());
49//!
50//! task.restart(Duration::from_secs(3), async move {
51//! // Some task here
52//! tokio::time::sleep(Duration::from_secs(1)).await;
53//! }).await;
54//! println!("Task timer is running: {}", !task.finished());
55//! assert!(!task.finished());
56//!
57//! task.stop().await;
58//! println!("Task timer is stoped: {}", task.finished());
59//! assert!(task.finished());
60//! }
61//! ```
62//!
63//! [async_channel]: https://crates.io/crates/async-channel
64//! [Notify]: https://docs.rs/tokio/1.44.2/tokio/sync/struct.Notify.html
65//! [reset]: Timeout::reset()
66//! [restart]: Timeout::restart()
67//! [stop]: Timeout::stop()
68//! [finished]: Timeout::finished()
69mod timeout;
70
71pub use timeout::Timeout;