aboutsummaryrefslogtreecommitdiffstats
path: root/src/timer.rs
blob: e3d7b6275d7d0f424323135ff55bb1e38a1b9fc3 (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! Timer wheel for scheduling periodic and one-shot
//! callbacks without threads or async.
//!
//! The event loop calls `tick()` each iteration to
//! fire expired timers.

use std::collections::{BTreeMap, HashMap};
use std::time::{Duration, Instant};

/// Opaque timer identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimerId(u64);

/// A simple timer wheel driven by the event loop.
///
/// Timers are stored in a BTreeMap keyed by deadline,
/// which gives O(log n) insert/cancel and efficient
/// scanning of expired timers.
pub struct TimerWheel {
    deadlines: BTreeMap<Instant, Vec<TimerId>>,
    intervals: HashMap<TimerId, Duration>,
    next_id: u64,
}

impl TimerWheel {
    pub fn new() -> Self {
        Self {
            deadlines: BTreeMap::new(),
            intervals: HashMap::new(),
            next_id: 0,
        }
    }

    /// Schedule a one-shot timer that fires after `delay`.
    pub fn schedule(&mut self, delay: Duration) -> TimerId {
        let id = self.alloc_id();
        let deadline = Instant::now() + delay;
        self.deadlines.entry(deadline).or_default().push(id);
        id
    }

    /// Schedule a repeating timer that fires every
    /// `interval`, starting after one interval.
    pub fn schedule_repeating(&mut self, interval: Duration) -> TimerId {
        let id = self.alloc_id();
        let deadline = Instant::now() + interval;
        self.deadlines.entry(deadline).or_default().push(id);
        self.intervals.insert(id, interval);
        id
    }

    /// Cancel a pending timer.
    ///
    /// Returns `true` if the timer was found and removed.
    pub fn cancel(&mut self, id: TimerId) -> bool {
        self.intervals.remove(&id);

        let mut found = false;

        // Remove from deadline map
        let mut empty_keys = Vec::new();
        for (key, ids) in self.deadlines.iter_mut() {
            if let Some(pos) = ids.iter().position(|i| *i == id) {
                ids.swap_remove(pos);
                found = true;
                if ids.is_empty() {
                    empty_keys.push(*key);
                }
                break;
            }
        }
        for k in empty_keys {
            self.deadlines.remove(&k);
        }
        found
    }

    /// Fire all expired timers, returning their IDs.
    ///
    /// Repeating timers are automatically rescheduled.
    /// Call this once per event loop iteration.
    pub fn tick(&mut self) -> Vec<TimerId> {
        let now = Instant::now();
        let mut fired = Vec::new();

        // Collect all deadlines <= now
        let expired: Vec<Instant> =
            self.deadlines.range(..=now).map(|(k, _)| *k).collect();

        for deadline in expired {
            if let Some(ids) = self.deadlines.remove(&deadline) {
                for id in ids {
                    fired.push(id);

                    // Reschedule if repeating
                    if let Some(&interval) = self.intervals.get(&id) {
                        let next = now + interval;
                        self.deadlines.entry(next).or_default().push(id);
                    }
                }
            }
        }

        fired
    }

    /// Duration until the next timer fires, or `None`
    /// if no timers are scheduled.
    ///
    /// Useful for determining the poll timeout.
    pub fn next_deadline(&self) -> Option<Duration> {
        self.deadlines.keys().next().map(|deadline| {
            let now = Instant::now();
            if *deadline <= now {
                Duration::ZERO
            } else {
                *deadline - now
            }
        })
    }

    /// Number of pending timers.
    pub fn pending_count(&self) -> usize {
        self.deadlines.values().map(|v| v.len()).sum()
    }

    /// Check if there are no pending timers.
    pub fn is_empty(&self) -> bool {
        self.deadlines.is_empty()
    }

    fn alloc_id(&mut self) -> TimerId {
        let id = TimerId(self.next_id);
        self.next_id += 1;
        id
    }
}

impl Default for TimerWheel {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn schedule_and_tick() {
        let mut tw = TimerWheel::new();
        let id = tw.schedule(Duration::from_millis(10));

        // Not yet expired
        assert!(tw.tick().is_empty());
        assert_eq!(tw.pending_count(), 1);

        // Wait and tick
        thread::sleep(Duration::from_millis(15));
        let fired = tw.tick();
        assert_eq!(fired, vec![id]);
        assert!(tw.is_empty());
    }

    #[test]
    fn cancel_timer() {
        let mut tw = TimerWheel::new();
        let id = tw.schedule(Duration::from_millis(100));
        assert!(tw.cancel(id));
        assert!(tw.is_empty());

        // Cancel non-existent returns false
        assert!(!tw.cancel(TimerId(999)));
    }

    #[test]
    fn repeating_timer() {
        let mut tw = TimerWheel::new();
        let id = tw.schedule_repeating(Duration::from_millis(10));

        thread::sleep(Duration::from_millis(15));
        let fired = tw.tick();
        assert_eq!(fired, vec![id]);

        // Should be rescheduled, not empty
        assert_eq!(tw.pending_count(), 1);

        // Cancel the repeating timer
        tw.cancel(id);
        assert!(tw.is_empty());
    }

    #[test]
    fn next_deadline_empty() {
        let tw = TimerWheel::new();
        assert!(tw.next_deadline().is_none());
    }

    #[test]
    fn next_deadline_returns_duration() {
        let mut tw = TimerWheel::new();
        tw.schedule(Duration::from_secs(10));
        let d = tw.next_deadline().unwrap();
        assert!(d <= Duration::from_secs(10));
        assert!(d > Duration::from_secs(9));
    }

    #[test]
    fn multiple_timers_fire_in_order() {
        let mut tw = TimerWheel::new();
        let a = tw.schedule(Duration::from_millis(5));
        let b = tw.schedule(Duration::from_millis(10));

        thread::sleep(Duration::from_millis(15));
        let fired = tw.tick();
        assert!(fired.contains(&a));
        assert!(fired.contains(&b));
        assert!(tw.is_empty());
    }
}