1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
extern crate chrono;
use chrono::prelude::*;
use chrono::{DateTime, Duration, Local, Utc};

use std::thread;

pub struct Metronome {
    interval: Duration,
    pub wake_time: DateTime<Utc>,
}

impl Metronome {
    pub fn new(interval: Duration) -> Metronome {
        Metronome {
            interval: interval,
            wake_time: Utc::now(),
        }
    }

    pub fn sleep(&mut self) {
        self.wake_time = self.wake_time + self.interval;
        let delta_s = self.wake_time.timestamp() - Utc::now().timestamp();
        let delta_ms = self.wake_time.timestamp_subsec_millis() as i32 - Utc::now().timestamp_subsec_millis() as i32;
        let duration = Duration::seconds(delta_s) + Duration::milliseconds(delta_ms as i64);
        if duration > Duration::zero() {
            duration.to_std().and_then(|d| Ok(thread::sleep(d)));
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}