blob: 0bd0d1384762f63069596a6df4f70111e12cf128 (
plain) (
blame)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
|
use chrono::{DateTime, Duration, Utc};
use std::thread;
use std::time::Duration as StdDuration;
pub struct Timer {
due: DateTime<Utc>,
duration: Duration,
}
impl Timer {
pub fn new(duration_in_ms: u64) -> Timer {
let duration = Duration::milliseconds(duration_in_ms as i64);
Timer {
due: Utc::now() + duration,
duration: duration,
}
}
pub fn await(&mut self) {
let due_time = (self.due.timestamp() * 1000) + self.due.timestamp_subsec_millis() as i64;
let now_time = {
let now = Utc::now();
(now.timestamp() * 1000) + now.timestamp_subsec_millis() as i64
};
if due_time > now_time {
let sleep_time = due_time - now_time;
if sleep_time > 0 {
thread::sleep(StdDuration::from_millis(sleep_time as u64));
}
}
self.due = self.due + self.duration;
}
pub fn check(&mut self) -> bool {
if Utc::now() >= self.due {
self.due = self.due + self.duration;
true
} else {
false
}
}
pub fn reset(&mut self) { self.due = Utc::now() + self.duration; }
}
|