Skip to main content

interval/
interval.rs

1use core::time::Duration;
2use std::time::Instant;
3
4static TEST_EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
5
6fn get_platform_time() -> Duration {
7    let epoch = TEST_EPOCH.get_or_init(Instant::now);
8    Instant::now().duration_since(*epoch)
9}
10
11fn main() {
12    let spawner: ato::Spawner<2> = ato::Spawner::default();
13    let start_time = get_platform_time();
14    // Run interval task for 3 iterations (500 ms), with sleep in between, which
15    // should still be 1500 ms total.
16    ato::spawn_task!(spawner, res, {
17        let mut interval =
18            ato::interval::Interval::new(Duration::from_millis(500), get_platform_time);
19        for _ in 0..3 {
20            interval.tick().await;
21            // sleep for random duration less than the interval
22            ato::sleep(Duration::from_millis(200), get_platform_time).await;
23        }
24    });
25    assert!(res.is_ok());
26    assert!(spawner.run_until_all_done().is_ok());
27
28    let elapsed = get_platform_time() - start_time;
29    assert!(elapsed <= Duration::from_millis(1550)); // with some margin
30}