You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.1 KiB
41 lines
1.1 KiB
//! A timed loop implementation
|
|
//!
|
|
//! This is a utility to be used in the server simulation to make sure
|
|
//! that a simulation step takes a certain amount of time to execute.
|
|
|
|
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(crate) 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(crate) fn spawn_loop<F>(run: Arc<AtomicBool>, f: F)
|
|
where
|
|
F: Future<Output = ()> + Send + Copy + 'static,
|
|
{
|
|
task::spawn(async move { block_loop(run, f) });
|
|
}
|
|
|