aboutsummaryrefslogtreecommitdiff
path: root/games/rstnode/src/_loop.rs
blob: 8623254903227a5fefa6b091c02a24e695573293 (plain)
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
//! A timed loop implementation

use async_std::{future::Future, task};
use chrono::{DateTime, Utc};
use std::{
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    time::Duration,
};

/// Number of ticks per second
#[from_env("RSTNODE_TICKS")]
const TICKS: u64 = 100;
const TICK_TIME: Duration = Duration::from_millis(1000 / TICKS);

/// Run a timed loop until you no longer want to
pub fn block_loop<F>(run: Arc<AtomicBool>, f: F)
where
    F: Future<Output = ()> + Send + Copy + 'static,
{
    while run.load(Ordering::Relaxed) {
        let t1 = Utc::now();
        task::block_on(f);
        let t2 = Utc::now();
        let t3 = (t2 - t1).to_std().unwrap();
        task::block_on(async { task::sleep(TICK_TIME - t3) });
    }
}

/// Run a detached timed loop until you no longer want to
pub fn spawn_loop<F>(run: Arc<AtomicBool>, f: F)
where
    F: Future<Output = ()> + Send + Copy + 'static,
{
    task::spawn(async move { block_loop(run, f) });
}