stable_flight/timing.rs
1//! Fixed-rate scheduling driven by the flight loop's `dt`, for streams (telemetry, heartbeats)
2//! that run slower than the loop.
3//!
4//! A tick rarely divides a stream's period, so [`Every`] carries the leftover time into the
5//! next period instead of discarding it: a 10 Hz stream on a 60 Hz loop sends 10 times per
6//! second, not 60 / 7 ≈ 8.6. A gap longer than a period (a stalled tick) fires once and
7//! drops the backlog rather than bursting.
8
9use core::time::Duration;
10
11#[cfg(test)]
12mod tests;
13
14/// Fires on the first call, then once per `interval` of accumulated `dt`.
15///
16/// # Examples
17///
18/// ```
19/// use core::time::Duration;
20/// use stable_flight::timing::Every;
21///
22/// // A 10 Hz stream on a 250 Hz loop.
23/// let mut heartbeat = Every::new(Duration::from_millis(100));
24/// let dt = Duration::from_millis(4);
25/// let fired = (0..250).filter(|_| heartbeat.ready(dt)).count();
26/// assert_eq!(fired, 11); // the first call, then 10 per second
27/// ```
28#[derive(Debug, Clone)]
29pub struct Every {
30 interval: Duration,
31 /// Time accumulated toward the next firing; always below `interval` between calls.
32 elapsed: Duration,
33}
34
35impl Every {
36 /// Fires on the first call, then once per `interval`.
37 pub fn new(interval: Duration) -> Self {
38 Every {
39 interval,
40 elapsed: interval,
41 }
42 }
43
44 /// Advances by `dt`. Returns `true` when a period has elapsed since the last firing.
45 pub fn ready(&mut self, dt: Duration) -> bool {
46 self.elapsed += dt;
47 if self.elapsed < self.interval {
48 return false;
49 }
50 self.elapsed -= self.interval;
51 if self.elapsed >= self.interval {
52 self.elapsed = Duration::ZERO;
53 }
54 true
55 }
56}