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