1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use rand::distributions::uniform::SampleRange;
use tokio::time;

use crate::random_number;

/// Util to asynchronously wait for `ms` milliseconds.
/// 
/// ### Examples
/// 
/// ```
/// use cs_utils::asyn::wait;
/// use tokio::time::{Instant, Duration};
/// 
/// #[tokio::main]
/// async fn main() {
///     let start_time = Instant::now();
///     println!("start");
///     wait(1000).await;
///     println!("end");
///     
///     assert!(
///         (Instant::now() - start_time) >= Duration::from_millis(1000),
///     );
/// }
/// 
/// ```
pub async fn wait(ms: u64) {
    time::sleep(time::Duration::from_millis(ms)).await;
}

/// Util to asynchronously wait for some random number milliseconds.
/// 
/// ### Examples
/// 
/// ```
/// use cs_utils::asyn::wait_random;
/// use tokio::time::{Instant, Duration};
/// 
/// #[tokio::main]
/// async fn main() {
///     let start_time = Instant::now();
///     println!("start");
///     wait_random(500..1000).await;
///     println!("end");
///     
///     assert!(
///         (Instant::now() - start_time) >= Duration::from_millis(500),
///     );
/// 
///     assert!(
///         (Instant::now() - start_time) <= Duration::from_millis(1000 + 100),
///     );
/// }
/// 
/// ```
pub async fn wait_random<T: SampleRange<u64>>(range: T) {
    let ms = random_number(range);

    time::sleep(time::Duration::from_millis(ms)).await;
}