1 use std::boxed::Box; 2 use std::time::{Duration, Instant}; 3 use std::{print, println}; 4 5 use crate::error::runtime_error::RuntimeError; 6 7 /// 伪定时器,结合主循环来实现计时,在计时器触发时,会执行相应的cmd命令 8 /// 后续实现线程后,应使用线程实现 9 pub struct Timer { 10 // 在创建计时器时记录当前时间 11 instant: Instant, 12 // 计时器触发时执行的闭包 13 callback: Box<dyn FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static>, 14 // 计时时长 15 duration: Duration, 16 // 此计时器的拥有者(Unit) 17 parent: usize, 18 } 19 20 impl Timer { 21 /// ## 创建计时任务 22 pub fn new( 23 duration: Duration, 24 callback: Box<dyn FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static>, 25 parent: usize, 26 ) -> Self { 27 Timer { 28 instant: Instant::now(), 29 callback: callback, 30 duration: duration, 31 parent: parent, 32 } 33 } 34 35 /// ## 判断当前是否到时,若执行该函数时已到时,将会执行定时任务 36 /// 37 /// ### return 到时返回true,否则返回false 38 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 51 pub fn parent(&self) -> usize { 52 self.parent 53 } 54 } 55