1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use crate::timer::Timer;
5
6pub struct TimerManager {
8 timers: Arc<Mutex<HashMap<u64, Timer>>>,
9 next_id: Arc<Mutex<u64>>,
10}
11
12impl Default for TimerManager {
13 fn default() -> Self {
14 Self::new()
15 }
16}
17
18impl TimerManager {
19 pub fn new() -> Self {
21 TimerManager {
22 timers: Arc::new(Mutex::new(HashMap::new())),
23 next_id: Arc::new(Mutex::new(0)),
24 }
25 }
26
27 pub fn add_timer(&self, timer: Timer) -> u64 {
29 let mut timers = self.timers.lock().unwrap();
30 let mut next_id = self.next_id.lock().unwrap();
31 let id = *next_id;
32 *next_id += 1;
33
34 timers.insert(id, timer);
35 id
36 }
37
38 pub fn stop_all(&self) {
40 let mut timers = self.timers.lock().unwrap();
41 for timer in timers.values_mut() {
42 let _ = timer.stop();
43 }
44 }
45
46 pub fn list_timers(&self) -> Vec<u64> {
48 self.timers
49 .lock()
50 .unwrap()
51 .iter()
52 .filter_map(|(id, timer)| {
53 if futures::executor::block_on(timer.get_state()) != crate::timer::TimerState::Stopped {
54 Some(*id)
55 } else {
56 None
57 }
58 })
59 .collect()
60 }
61
62 pub fn get_timer(&self, id: u64) -> Option<Arc<Mutex<Timer>>> {
64 self.timers.lock().unwrap().get(&id).cloned().map(|timer| Arc::new(Mutex::new(timer)))
65 }
66}
67
68unsafe impl Send for TimerManager {}
69unsafe impl Sync for TimerManager {}