diff options
author | Katharina Fey <kookie@spacekookie.de> | 2021-02-06 19:40:53 +0100 |
---|---|---|
committer | Katharina Fey <kookie@spacekookie.de> | 2021-02-06 19:42:04 +0100 |
commit | cf9392a33bb99ae581f818d3ddb8be1231521a02 (patch) | |
tree | 8295d8a4ed199c3263eadd8f1a508b98567a44f7 /games/rstnode/rst-core/src/_loop.rs | |
parent | 56d96b2f22bf6a61ff992b000215dc3a2c2448ad (diff) |
rstnode: restructure project into workspace and sub-crates
Diffstat (limited to 'games/rstnode/rst-core/src/_loop.rs')
-rw-r--r-- | games/rstnode/rst-core/src/_loop.rs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/games/rstnode/rst-core/src/_loop.rs b/games/rstnode/rst-core/src/_loop.rs new file mode 100644 index 000000000000..ac4619622ed3 --- /dev/null +++ b/games/rstnode/rst-core/src/_loop.rs @@ -0,0 +1,41 @@ +//! 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) }); +} |