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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a one-time job to be
//! scheduled for whatever time the user desires.
//!
//! We are using chrono's `DateTime<Utc>`, enabling you to serialise and thus
//! backup currently running tasks,
//! in case you want to shutdown/restart your application,
//! constructing a new scheduler is doable.
//! However, please make sure your internal clock is synced.
#![deny(rust_2018_idioms)]
use chrono::Duration as ChronoDuration;
use parking_lot::{Condvar, Mutex, RwLock};
use std::{cmp::Ordering, collections::BinaryHeap, sync::Arc, time::Duration as StdDuration};
use threadpool::ThreadPool;

pub use chrono::{DateTime, Duration, Utc};

/// Compare if an `enum`-variant matches another variant.
macro_rules! cmp_variant {
    ($expression:expr, $($variant:tt)+) => {
        match $expression {
            $($variant)+ => true,
            _ => false
        }
    }
}

/// When a task is due, this will be passed to the task.
/// Currently, there is not much use to this. However, this might be extended
/// in the future.
pub struct Context {
    time: DateTime<Utc>,
}

/// Every task will return this `enum`.
pub enum DateResult {
    /// The task is considered finished and can be fully removed.
    Done,
    /// The task will be scheduled for a new date on passed `DateTime<Utc>`.
    Repeat(DateTime<Utc>),
}

/// Every job gets a planned `Date` with the scheduler.
pub struct Date {
    pub context: Context,
    pub job: Box<dyn FnMut(&mut Context) -> DateResult + Send + Sync + 'static>,
}

impl Eq for Date {}

/// Invert comparisions to create a min-heap.
impl Ord for Date {
    fn cmp(&self, other: &Date) -> Ordering {
        match self.context.time.cmp(&other.context.time) {
            Ordering::Less => Ordering::Greater,
            Ordering::Greater => Ordering::Less,
            Ordering::Equal => Ordering::Equal,
        }
    }
}

/// Invert comparisions to create a min-heap.
impl PartialOrd for Date {
    fn partial_cmp(&self, other: &Date) -> Option<Ordering> {
        Some(match self.context.time.cmp(&other.context.time) {
            Ordering::Less => Ordering::Greater,
            Ordering::Greater => Ordering::Less,
            Ordering::Equal => Ordering::Equal,
        })
    }
}

impl PartialEq for Date {
    fn eq(&self, other: &Date) -> bool {
        self.context.time == other.context.time
    }
}

/// The [`Scheduler`]'s worker thread switches through different states
/// while running, each state changes the behaviour.
///
/// [`Scheduler`]: struct.Scheduler.html
enum SchedulerState {
    /// No dates being awaited, sleep until one gets added.
    PauseEmpty,
    /// Pause until next date is due.
    PauseTime(StdDuration),
    /// If the next date is already waiting to be executed,
    /// the thread continues running without sleeping.
    Run,
    /// Exits the thread.
    Exit,
}

impl SchedulerState {
    fn is_running(&self) -> bool {
        cmp_variant!(*self, SchedulerState::Run)
    }

    fn new_pause_time(duration: ChronoDuration) -> Self {
        SchedulerState::PauseTime(
            duration
                .to_std()
                .unwrap_or_else(|_| StdDuration::from_millis(0)),
        )
    }
}

/// This scheduler exists on two levels: The handle, granting you the
/// ability of adding new tasks, and the executor, dating and executing these
/// tasks when specified time is met.
///
/// **Info**: This scheduler may not be precise due to anomalies such as
/// preemption or platform differences.
pub struct Scheduler {
    /// The mean of communication with the running scheduler.
    condvar: Arc<(Mutex<SchedulerState>, Condvar)>,
    /// Every job has its date listed inside this.
    dates: Arc<RwLock<BinaryHeap<Date>>>,
}

impl Scheduler {
    /// Add a task to be executed when `time` is reached.
    pub fn add_task_datetime<T>(&mut self, time: DateTime<Utc>, to_execute: T)
    where
        T: FnMut(&mut Context) -> DateResult + Send + Sync + 'static,
    {
        let &(ref state_lock, ref notifier) = &*self.condvar;

        let task = Date {
            context: Context { time },
            job: Box::new(to_execute),
        };

        let mut locked_heap = self.dates.write();

        if locked_heap.is_empty() {
            let mut scheduler_state = state_lock.lock();
            let left = task.context.time.signed_duration_since(Utc::now());

            if !scheduler_state.is_running() {
                *scheduler_state = SchedulerState::new_pause_time(left);
                notifier.notify_one();
            }
        } else {
            let mut scheduler_state = state_lock.lock();

            if let SchedulerState::PauseTime(_) = *scheduler_state {
                let peeked = locked_heap.peek().expect("Expected heap to be filled.");

                if task.context.time < peeked.context.time {
                    let left = task.context.time.signed_duration_since(Utc::now());

                    if !scheduler_state.is_running() {
                        *scheduler_state = SchedulerState::PauseTime(
                            left.to_std()
                                .unwrap_or_else(|_| StdDuration::from_millis(0)),
                        );
                        notifier.notify_one();
                    }
                }
            }
        }

        locked_heap.push(task);
    }

    pub fn add_task_duration<T>(&mut self, how_long: ChronoDuration, to_execute: T)
    where
        T: FnMut(&mut Context) -> DateResult + Send + Sync + 'static,
    {
        let time = Utc::now() + how_long;
        self.add_task_datetime(time, to_execute);
    }
}

fn set_state_lock(state_lock: &Mutex<SchedulerState>, to_set: SchedulerState) {
    let mut state = state_lock.lock();
    *state = to_set;
}

#[inline]
fn _push_and_notfiy(date: Date, heap: &mut BinaryHeap<Date>, notifier: &Condvar) {
    heap.push(date);
    notifier.notify_one();
}

/// This function pushes a `date` onto `data_pooled` and notifies the
/// dispatching-thread in case they are sleeping.
#[inline]
fn push_and_notfiy(
    dispatcher_pair: &Arc<(Mutex<SchedulerState>, Condvar)>,
    data_pooled: &Arc<RwLock<BinaryHeap<Date>>>,
    when: &DateTime<Utc>,
    date: Date,
) {
    let &(ref state_lock, ref notifier) = &**dispatcher_pair;

    let mut state = state_lock.lock();

    let mut heap_lock = data_pooled.write();

    if let Some(peek) = heap_lock.peek() {
        if peek.context.time < *when {
            let left = peek.context.time.signed_duration_since(Utc::now());

            *state = SchedulerState::new_pause_time(left);
            _push_and_notfiy(date, &mut heap_lock, &notifier);
        } else {
            let left = when.signed_duration_since(Utc::now());

            *state = SchedulerState::new_pause_time(left);
            _push_and_notfiy(date, &mut heap_lock, &notifier);
        }
    } else {
        let left = when.signed_duration_since(Utc::now());

        *state = SchedulerState::new_pause_time(left);
        _push_and_notfiy(date, &mut heap_lock, &notifier);
    }

}

#[must_use]
enum Break {
    Yes,
    No,
}

#[inline]
fn process_states(state_lock: &Mutex<SchedulerState>, notifier: &Condvar) -> Break {
    let mut scheduler_state = state_lock.lock();

    while let SchedulerState::PauseEmpty = *scheduler_state {
        notifier.wait(&mut scheduler_state);
    }

    while let SchedulerState::PauseTime(duration) = *scheduler_state {
        if notifier
            .wait_for(&mut scheduler_state, duration)
            .timed_out()
        {
            break;
        }
    }

    if let SchedulerState::Exit = *scheduler_state {
        return Break::Yes;
    }

    Break::No
}

fn dispatch_date(
    threadpool: &ThreadPool,
    dates: &Arc<RwLock<BinaryHeap<Date>>>,
    pair_scheduler: &Arc<(Mutex<SchedulerState>, Condvar)>,
) {
    let mut date = {
        let mut dates = dates.write();

        dates.pop().expect("Should not run on empty heap.")
    };

    let date_dispatcher = dates.clone();
    let dispatcher_pair = pair_scheduler.clone();

    threadpool.execute(move || {
        if let DateResult::Repeat(when) = (date.job)(&mut date.context) {
            date.context.time = when;

            push_and_notfiy(&dispatcher_pair, &date_dispatcher, &when, date);
        }
    });
}

fn check_peeking_date(dates: &Arc<RwLock<BinaryHeap<Date>>>, state_lock: &Mutex<SchedulerState>) {
    if let Some(next) = dates.read().peek() {
        let now = Utc::now();

        if next.context.time > now {
            let left = next.context.time.signed_duration_since(now);

            set_state_lock(&state_lock, SchedulerState::new_pause_time(left));
        } else {
            set_state_lock(&state_lock, SchedulerState::Run);
        }
    } else {
        set_state_lock(&state_lock, SchedulerState::PauseEmpty);
    }
}

impl Scheduler {
    /// Creates a new [`Scheduler`] which will use `thread_count` number of
    /// threads when tasks are being dispatched/dated.
    ///
    /// [`Scheduler`]: struct.Scheduler.html
    pub fn new(thread_count: usize) -> Self {
        let pair = Arc::new((Mutex::new(SchedulerState::PauseEmpty), Condvar::new()));
        let pair_scheduler = pair.clone();
        let dates: Arc<RwLock<BinaryHeap<Date>>> = Arc::new(RwLock::new(BinaryHeap::new()));

        let dates_scheduler = Arc::clone(&dates);
        std::thread::spawn(move || {
            let &(ref state_lock, ref notifier) = &*pair_scheduler;
            let threadpool = ThreadPool::new(thread_count);

            loop {
                if let Break::Yes = process_states(&state_lock, &notifier) {
                    break;
                }

                dispatch_date(&threadpool, &dates_scheduler, &pair_scheduler);

                check_peeking_date(&dates_scheduler, &state_lock);
            }
        });

        Scheduler {
            condvar: pair,
            dates,
        }
    }
}

/// Once the scheduler is dropped, we also need to join and finish the thread.
impl<'a> Drop for Scheduler {
    fn drop(&mut self) {
        let &(ref state_lock, ref notifier) = &*self.condvar;

        let mut state = state_lock.lock();
        *state = SchedulerState::Exit;
        notifier.notify_one();
    }
}