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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use std::cmp::Ordering;
use std::collections::binary_heap::BinaryHeap;
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use instant_iter::IntoInstantIter;
pub struct Planner {
job_queue: Arc<Mutex<BinaryHeap<Job>>>,
job_processor_tx: Arc<Mutex<Option<mpsc::Sender<()>>>>,
}
impl Planner {
#[allow(missing_docs)]
pub fn new() -> Planner {
Planner {
job_queue: Arc::new(Mutex::new(BinaryHeap::new())),
job_processor_tx: Arc::new(Mutex::new(None)),
}
}
pub fn add<T: Iterator<Item = Instant> + Send + Sync + 'static>(
&mut self,
callback: impl Fn() -> () + Send + Sync + 'static,
times: impl IntoInstantIter<IterType = T>,
)
{
let job = Job::new(callback, times)
.expect("Added job with no execution times");
let job_next_time = job.next_time;
self.job_queue.lock().unwrap().push(job);
let is_earliest_job = match self.job_queue.lock().unwrap().peek() {
Some(earliest_job) => job_next_time == earliest_job.next_time,
None => false,
};
if self.is_started() && is_earliest_job {
Self::spawn_waker(
self.job_processor_tx.lock().unwrap().clone(),
job_next_time.duration_since(Instant::now()),
);
}
if !self.is_started() {
self.start();
}
}
pub fn start(&mut self) {
if self.is_started() {
return;
}
let (job_processor_tx, job_processor_rx) = mpsc::channel();
*self.job_processor_tx.lock().unwrap() = Some(job_processor_tx.clone());
let job_queue = self.job_queue.clone();
let job_processor_tx = self.job_processor_tx.clone();
Self::spawn("planner", move || loop {
let mut job_queue_locked = job_queue.lock().unwrap();
let next_time = job_queue_locked.peek().map(|job| job.next_time);
let now = Instant::now();
if next_time.is_none() {
*job_processor_tx.lock().unwrap() = None;
break;
}
if next_time.unwrap() <= now {
let job = job_queue_locked.pop().expect(
"Job disappeared from queue while queue was locked",
);
let spawn_callback = job.callback.clone();
Self::spawn("exec_callback", move || (*spawn_callback)());
job.to_next_time()
.map(|new_job| job_queue_locked.push(new_job));
continue;
}
drop(job_queue_locked);
Self::spawn_waker(
job_processor_tx.lock().unwrap().clone(),
next_time.unwrap().duration_since(Instant::now()),
);
job_processor_rx
.recv()
.expect("Couldn't listen for waking messages");
});
}
fn is_started(&self) -> bool {
self.job_processor_tx.lock().unwrap().is_some()
}
fn spawn_waker(
job_processor_tx: Option<mpsc::Sender<()>>,
duration: Duration,
)
{
Self::spawn("waker", move || {
thread::sleep(duration);
job_processor_tx.map(|tx| tx.send(()));
});
}
fn spawn(
name: impl ::std::fmt::Display,
callback: impl FnOnce() -> () + Send + 'static,
)
{
let name = format!("{}_{}", env!("CARGO_PKG_NAME"), name);
thread::Builder::new()
.name(name.into())
.spawn(callback)
.expect("Failed to spawn thread with name");
}
}
struct Job {
callback: Arc<Fn() -> () + Send + Sync + 'static>,
next_time: Instant,
rest_times: Box<Iterator<Item = Instant> + Send + Sync>,
}
impl Job {
fn new<T: Iterator<Item = Instant> + Send + Sync + 'static>(
callback: impl Fn() -> () + Send + Sync + 'static,
times: impl IntoInstantIter<IterType = T>,
) -> Option<Job>
{
let mut times = times.into_instant_iter();
times.next().map(|next_time| Job {
callback: Arc::new(callback),
next_time,
rest_times: Box::new(times),
})
}
fn to_next_time(mut self) -> Option<Job> {
self.rest_times.next().map(|new_next_time| Job {
callback: self.callback,
next_time: new_next_time,
rest_times: self.rest_times,
})
}
}
impl Ord for Job {
fn cmp(&self, other: &Job) -> Ordering {
other.next_time.cmp(&self.next_time)
}
}
impl PartialOrd for Job {
fn partial_cmp(&self, other: &Job) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for Job {}
impl PartialEq for Job {
fn eq(&self, other: &Job) -> bool { self.next_time == other.next_time }
}