1 use std::time::{Duration, Instant}; 2 3 use crate::{error::runtime_error::RuntimeError, unit::timer::TimerUnit}; 4 5 /// 伪定时器,结合主循环来实现计时,在计时器触发时,会执行相应的cmd命令 6 /// 后续实现线程后,应使用线程实现 7 pub struct Timer { 8 // 在创建计时器时记录当前时间 9 instant: Instant, 10 // 计时器触发时执行的闭包 11 callback: Box<dyn FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static>, 12 // 计时时长 13 duration: Duration, 14 // 此计时器的拥有者(Unit) 15 parent: usize, 16 } 17 18 impl Timer { 19 /// ## 创建计时任务 20 //要new一个unit!!,查询id命名规则 new( duration: Duration, callback: Box<dyn FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static>, parent: usize, ) -> Self21 pub fn new( 22 duration: Duration, 23 callback: Box<dyn FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static>, 24 parent: usize, 25 ) -> Self { 26 let _timerunit = TimerUnit::default(); 27 Timer { 28 instant: Instant::now(), 29 callback: callback, 30 duration: duration, 31 parent: parent, 32 } 33 } 34 35 /// ## 判断当前是否到时,若执行该函数时已到时,将会执行定时任务 36 /// 37 /// ### return 到时返回true,否则返回false check(&mut self) -> bool38 pub fn check(&mut self) -> bool { 39 // println!("{},{}",self.instant.elapsed().as_micros(),self.duration.as_micros()); 40 if self.instant.elapsed().saturating_sub(self.duration) > Duration::ZERO { 41 // TODO: 未进行错误处理 42 if let Err(_e) = (self.callback)() { 43 println!("task error"); 44 } 45 return true; 46 } 47 return false; 48 } 49 50 /// ## 获取此计时器的拥有者Unit parent(&self) -> usize51 pub fn parent(&self) -> usize { 52 self.parent 53 } 54 } 55