1#![forbid(unsafe_code)]
6
7use futures::future::FusedFuture;
8use std::time::Duration;
9use wgame_app::{
10 runtime::sleep_until,
11 sleep,
12 time::{Instant, Timer},
13};
14
15pub struct PeriodicTimer {
20 timer: Timer,
21 period: Duration,
22}
23
24impl PeriodicTimer {
25 pub fn new(period: Duration) -> Self {
31 assert!(!period.is_zero(), "Timer period must be positive");
32 Self {
33 timer: sleep(period),
34 period,
35 }
36 }
37
38 pub fn period(&self) -> Duration {
40 self.period
41 }
42
43 pub fn elapsed_periods(&mut self) -> Duration {
45 if self.timer.is_terminated() {
46 let now = Instant::now();
47 let (next_timestamp, elapsed) = advance(self.timer.timestamp(), now, self.period);
48 self.timer = sleep_until(next_timestamp);
49 elapsed
50 } else {
51 Duration::ZERO
52 }
53 }
54
55 pub async fn wait_next(&mut self) -> Duration {
57 (&mut self.timer).await;
58 self.elapsed_periods()
59 }
60}
61
62fn advance(deadline: Instant, now: Instant, period: Duration) -> (Instant, Duration) {
63 let late = now - deadline;
64 let rem = late.as_nanos() % period.as_nanos();
65 let remainder = Duration::new((rem / 1_000_000_000) as u64, (rem % 1_000_000_000) as u32);
66 let elapsed = late - remainder + period;
67 (deadline + elapsed, elapsed)
68}
69#[cfg(test)]
70mod tests {
71 use super::*;
72 #[test]
73 fn periodic_deadlines_keep_phase_and_count_missed_ticks() {
74 let start = Instant::now();
75 let period = Duration::from_millis(10);
76 assert_eq!(advance(start, start, period), (start + period, period));
77 assert_eq!(
78 advance(start, start + Duration::from_millis(25), period),
79 (start + Duration::from_millis(30), Duration::from_millis(30))
80 );
81 }
82}