supervisor_rs/
timer.rs

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
8/// Timer struct
9pub struct Timer {
10    name: String,
11    id: u32,
12    comm: String,
13    interval: time::Duration,
14}
15
16impl Timer {
17    /// new timer
18    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    /// generate new timer from child name and child config
28    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    /// run the timer
45    pub fn run(self, kig: Arc<Mutex<Kindergarten>>) {
46        thread::sleep(self.interval);
47
48        //check if this timer still works
49        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        // call server::day_care to run the repeat command
62        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    /// check this timer is outdate or not
80    fn check(&self, kig: Arc<Mutex<Kindergarten>>) -> bool {
81        let mut kg = kig.lock().unwrap();
82        // if timer.id not equal child.id, means child has already restarted
83        // then this timer is outdate
84        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}