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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
use rand::distributions::uniform::SampleRange;
use tokio::time;
use crate::random_number;
/// Asynchronously wait for `ms` milliseconds.
///
/// ### Examples
///
/// ```
/// use cs_utils::futures::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;
}
/// Asynchronously wait for `micros` microseconds.
///
/// ### Examples
///
/// ```
/// use cs_utils::futures::wait_micros;
/// use tokio::time::{Instant, Duration};
///
/// #[tokio::main]
/// async fn main() {
/// let start_time = Instant::now();
/// println!("start");
/// wait_micros(1000).await;
/// println!("end");
///
/// assert!(
/// (Instant::now() - start_time) >= Duration::from_micros(1000),
/// );
/// }
/// ```
pub async fn wait_micros(micros: u64) {
time::sleep(time::Duration::from_micros(micros)).await;
}
/// Asynchronously wait for `nanos` nanoseconds.
///
/// ### Examples
///
/// ```
/// use cs_utils::futures::wait_nanos;
/// use tokio::time::{Instant, Duration};
///
/// #[tokio::main]
/// async fn main() {
/// let start_time = Instant::now();
/// println!("start");
/// wait_nanos(1000).await;
/// println!("end");
///
/// assert!(
/// (Instant::now() - start_time) >= Duration::from_nanos(1000),
/// );
/// }
/// ```
pub async fn wait_nanos(nanos: u64) {
time::sleep(time::Duration::from_nanos(nanos)).await;
}
/// Asynchronously wait for some `random number` of milliseconds.
///
/// ### Examples
///
/// ```
/// use cs_utils::futures::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;
}