1use super::kindergarten::*;
2use super::server;
3use super::*;
4use std::io::{Error as ioError, ErrorKind, Result};
5use std::sync::{Arc, Mutex};
6use std::{thread, time};
7
8pub struct Timer {
10 name: String,
11 id: u32,
12 comm: String,
13 interval: time::Duration,
14}
15
16impl Timer {
17 fn new(name: &String, id: u32, comm: String, td: time::Duration) -> Self {
19 Timer {
20 name: name.clone(),
21 id,
22 comm,
23 interval: td,
24 }
25 }
26
27 pub fn new_from_conf(name: String, conf: child::Config) -> Result<Self> {
29 if !conf.is_repeat() {
30 return Err(ioError::new(
31 ErrorKind::InvalidInput,
32 format!("config is not repeatable"),
33 ));
34 }
35
36 Ok(Self::new(
37 &name,
38 conf.child_id.unwrap(),
39 format!("{}", conf.repeat_command().unwrap()),
40 conf.to_duration().unwrap(),
41 ))
42 }
43
44 pub fn run(self, kig: Arc<Mutex<Kindergarten>>) {
46 thread::sleep(self.interval);
47
48 if !self.check(kig.clone()) {
50 println!(
51 "{}",
52 logger::timelog(&format!(
53 "check failed when timer try to run \"{} {}\"",
54 self.comm.clone(),
55 self.name.clone()
56 ))
57 );
58 return;
59 }
60
61 match server::day_care(kig, format!("{} {}", self.comm.clone(), self.name.clone())) {
63 Err(e) => println!(
64 "{}",
65 logger::timelog(&format!("Timer is up, but {:?}", e.to_string()))
66 ),
67 Ok(m) => println!(
68 "{}\n{}",
69 logger::timelog(&format!(
70 "Timer is up, run \"{} {}\"",
71 self.comm.clone(),
72 self.name.clone(),
73 )),
74 logger::timelog(&m),
75 ),
76 }
77 }
78
79 fn check(&self, kig: Arc<Mutex<Kindergarten>>) -> bool {
81 let mut kg = kig.lock().unwrap();
82 if let Some(id) = kg.has_child(&self.name) {
85 if *id == self.id {
86 return true;
87 }
88 }
89
90 return false;
91 }
92}