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