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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use core::input::InputScope;
use std::time::Duration;
use std::thread;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
#[derive(Debug, Clone)]
pub struct CancelHandle(Arc<AtomicBool>);
impl CancelHandle {
fn new() -> CancelHandle {
CancelHandle(Arc::new(AtomicBool::new(false)))
}
pub fn cancel(&self) {
self.0.store(true, SeqCst);
}
fn is_cancelled(&self) -> bool {
self.0.load(SeqCst)
}
}
fn set_schedule<F>(every: Duration, operation: F) -> CancelHandle
where
F: Fn() -> () + Send + 'static,
{
let handle = CancelHandle::new();
let inner_handle = handle.clone();
thread::Builder::new()
.name("dipstick-scheduler".to_string())
.spawn(move || loop {
thread::sleep(every);
if inner_handle.is_cancelled() {
break;
}
operation();
})
.unwrap();
handle
}
pub trait ScheduleFlush {
fn flush_every(&self, period: Duration) -> CancelHandle;
}
impl<T: InputScope + Send + Sync + Clone + 'static> ScheduleFlush for T {
fn flush_every(&self, period: Duration) -> CancelHandle {
let scope = self.clone();
set_schedule(period, move || {
if let Err(err) = scope.flush() {
error!("Could not flush metrics: {}", err);
}
})
}
}