diff options
author | Katharina Fey <kookie@spacekookie.de> | 2021-01-29 11:25:05 +0100 |
---|---|---|
committer | Katharina Fey <kookie@spacekookie.de> | 2021-01-29 11:25:05 +0100 |
commit | 31ec889558d6a32d4861d7d14eff1f559e7ca72c (patch) | |
tree | c9bb875698d6ee3544eef864ddec2c9db561707f /games/rstnode/src/_loop.rs | |
parent | 9765d1e42dc9d1d3a90f54d87cebdd7ab4549417 (diff) | |
parent | 78d813b2a119b314349555387669f9c33727c5b1 (diff) |
Add 'games/rstnode/' from commit '78d813b2a119b314349555387669f9c33727c5b1'
git-subtree-dir: games/rstnode
git-subtree-mainline: 9765d1e42dc9d1d3a90f54d87cebdd7ab4549417
git-subtree-split: 78d813b2a119b314349555387669f9c33727c5b1
Diffstat (limited to 'games/rstnode/src/_loop.rs')
-rw-r--r-- | games/rstnode/src/_loop.rs | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/games/rstnode/src/_loop.rs b/games/rstnode/src/_loop.rs new file mode 100644 index 000000000000..7ba7ad7cdd27 --- /dev/null +++ b/games/rstnode/src/_loop.rs @@ -0,0 +1,37 @@ +//! 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 +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) }); +} |