forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtick_loop.rs
More file actions
38 lines (33 loc) · 1019 Bytes
/
tick_loop.rs
File metadata and controls
38 lines (33 loc) · 1019 Bytes
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
use std::time::Instant;
use base::TICK_DURATION;
/// Utility to invoke a function in a tick loop, once
/// every 50ms.
pub struct TickLoop {
function: Box<dyn FnMut() -> bool>,
}
impl TickLoop {
/// Creates a `TickLoop`. The given `function` is called
/// each tick. Returning `true` from `function` causes the
/// tick loop to exit.
pub fn new(function: impl FnMut() -> bool + 'static) -> Self {
Self {
function: Box::new(function),
}
}
/// Runs the tick loop until the callback returns `true`.
pub fn run(mut self) {
loop {
let start = Instant::now();
let should_exit = (self.function)();
if should_exit {
return;
}
let elapsed = start.elapsed();
if elapsed > TICK_DURATION {
log::warn!("Tick took too long ({:?})", elapsed);
} else {
std::thread::sleep(TICK_DURATION - elapsed);
}
}
}
}