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
use chrono::Duration;

pub trait Eventer {
    fn execute(&mut self) -> Option<Duration>;
}

/// A basic scheduled event. `task` will be called once when added to the scheduler.
/// A mutable reference to `state` will be passed to `task` on each call.
/// if `task` returns `Some(Duration)`, `task` will be rerun after that amount of time has passed.
/// if `task` returns `None`, the `BasicEvent` will be dropped
pub struct BasicEvent<F, T>
where
    F: FnMut(&mut T) -> Option<Duration>,
{
    pub task: F,
    pub state: T,
}

impl<F, T> Eventer for BasicEvent<F, T>
where
    F: FnMut(&mut T) -> Option<Duration>,
{
    fn execute(&mut self) -> Option<Duration> {
        (self.task)(&mut self.state)
    }
}

#[allow(dead_code)]
pub struct OneShot<F>
where
    F: Fn()
{
    delay: Option<Duration>,
    task: F,
}

impl<F> OneShot<F>
where
    F: Fn()
{
    #[allow(dead_code)]
    fn new(delay: Duration, task: F) -> Self {
        Self {
            delay: Some(delay),
            task: task
        }
    }
}

impl<F> Eventer for OneShot<F>
where
    F: Fn()
{
    fn execute(&mut self) -> Option<Duration> {
        if self.delay.is_some() {
            let mut x = None;
            ::std::mem::swap(&mut x, &mut self.delay);
            x
        } else {
            (self.task)();
            None
        }
    }
}