xref: /DragonReach/src/manager/timer_manager/mod.rs (revision dfd3fd9812f3584f9392934d1254e24d17661b2d)
1 use std::{sync::RwLock, time::Duration};
2 
3 use crate::{error::runtime_error::RuntimeError, time::timer::Timer};
4 use lazy_static::lazy_static;
5 
6 lazy_static! {
7     // 管理全局计时器任务
8     static ref TIMER_TASK_MANAGER: RwLock<TimerManager> = RwLock::new(TimerManager {
9         inner_timers: Vec::new()
10     });
11 }
12 
13 pub struct TimerManager {
14     inner_timers: Vec<Timer>,
15 }
16 
17 impl<'a> IntoIterator for &'a mut TimerManager {
18     type Item = &'a mut Timer;
19 
20     type IntoIter = std::slice::IterMut<'a, Timer>;
21 
22     fn into_iter(self) -> Self::IntoIter {
23         self.inner_timers.iter_mut()
24     }
25 }
26 
27 impl TimerManager {
28     /// ## 添加定时器任务
29     ///
30     /// 只有通过这个方式创建的Timer对象才会真正的实现计时
31     pub fn push_timer<F>(duration: Duration, callback: F, parent: usize)
32     where
33         F: FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static,
34     {
35         TIMER_TASK_MANAGER
36             .write()
37             .unwrap()
38             .inner_timers
39             .push(Timer::new(duration, Box::new(callback), parent));
40     }
41 
42     /// ## 检测定时器是否到时,到时则触发
43     ///
44     /// 该方法在主循环中每循环一次检测一次,是伪计时器的主运行函数
45     pub fn check_timer() {
46         let mut writer = TIMER_TASK_MANAGER.write().unwrap();
47         //此处触发定时器,若定时器被触发,则移除
48         writer.inner_timers.retain_mut(|x| !x.check());
49     }
50 
51     /// ## 取消掉一个unit的所有定时任务,
52     ///
53     /// 一般在unit启动失败或者退出unit时进行该操作
54     pub fn cancel_timer(unit_id: usize) {
55         TIMER_TASK_MANAGER
56             .write()
57             .unwrap()
58             .inner_timers
59             .retain(|x| x.parent() == unit_id)
60     }
61 }
62