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
use crate::error::SchedulerError;
use chrono::prelude::*;
use chrono_tz::Tz;
use std::convert::TryFrom;
use std::time::Duration;

pub enum Scheduler {
    /// Set to execute on set time periods
    Cron(cron::Schedule),

    /// Set to execute exactly `duration` away from the previous execution.
    /// If
    Interval {
        interval_duration: Duration,
        execute_at_startup: bool,
    },

    /// Set to execute to never
    Never,
}

impl Scheduler {
    // Determine the next time we should execute (from a reference point)
    pub fn next(&mut self, after: &DateTime<Utc>, timezone: Option<Tz>) -> Option<DateTime<Utc>> {
        match *self {
            Scheduler::Cron(ref cs) => {
                if let Some(tz) = timezone {
                    cs.after(&after.with_timezone(&tz))
                        .next()
                        .map(|date| date.with_timezone(&Utc))
                } else {
                    cs.after(&after).next()
                }
            }

            Scheduler::Interval {
                ref interval_duration,
                ref mut execute_at_startup,
            } => {
                if *execute_at_startup {
                    *execute_at_startup = false;
                    Some(*after)
                } else {
                    let ch_duration = match time::Duration::from_std(*interval_duration) {
                        Ok(value) => value,
                        Err(_) => {
                            return None;
                        }
                    };
                    Some(*after + ch_duration)
                }
            }

            Scheduler::Never => None,
        }
    }
}

impl<'a> TryFrom<&'a str> for Scheduler {
    type Error = SchedulerError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(Scheduler::Cron(value.parse().map_err(|err| {
            SchedulerError::ScheduleDefinitionError {
                message: format!("Cannot create schedule for [{}]. Err: {}", value, err),
            }
        })?))
    }
}

impl TryFrom<String> for Scheduler {
    type Error = SchedulerError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        use std::convert::TryInto;
        value.as_str().try_into()
    }
}

impl TryFrom<Duration> for Scheduler {
    type Error = SchedulerError;
    fn try_from(value: Duration) -> Result<Self, Self::Error> {
        Ok(Scheduler::Interval {
            interval_duration: value,
            execute_at_startup: false,
        })
    }
}

impl TryFrom<(Duration, bool)> for Scheduler {
    type Error = SchedulerError;
    fn try_from(value: (Duration, bool)) -> Result<Self, Self::Error> {
        Ok(Scheduler::Interval {
            interval_duration: value.0,
            execute_at_startup: value.1,
        })
    }
}

#[cfg(test)]
pub mod test {

    use super::*;
    use chrono_tz::UTC;
    use std::convert::TryInto;

    #[test]
    fn never_should_not_schedule() {
        let mut schedule = Scheduler::Never;
        assert_eq!(None, schedule.next(&Utc::now(), Some(UTC)))
    }

    #[test]
    fn interval_should_schedule_plus_duration() {
        let now = Utc::now();
        let secs = 10;
        let mut schedule: Scheduler = Duration::new(secs, 0).try_into().unwrap();

        let next = schedule.next(&now, None).unwrap();

        assert!(next.timestamp() >= now.timestamp() + (secs as i64));
    }

    #[test]
    fn interval_should_schedule_at_startup() {
        let now = Utc::now();
        let secs = 10;
        let mut schedule: Scheduler = (Duration::new(secs, 0), true).try_into().unwrap();

        let first = schedule.next(&now, None).unwrap();
        assert_eq!(now.timestamp(), first.timestamp());

        let next = schedule.next(&now, None).unwrap();
        assert!(next.timestamp() >= now.timestamp() + (secs as i64));
    }

    #[test]
    fn should_build_an_interval_schedule_from_duration() {
        let schedule: Scheduler = Duration::new(1, 1).try_into().unwrap();
        match schedule {
            Scheduler::Interval { .. } => assert!(true),
            _ => assert!(false),
        }
    }

    #[test]
    fn should_build_a_periodic_schedule_from_str() {
        let schedule: Scheduler = "* * * * * *".try_into().unwrap();
        match schedule {
            Scheduler::Cron(_) => assert!(true),
            _ => assert!(false),
        }
    }

    #[test]
    fn cron_should_be_time_zone_aware_with_utc() {
        let mut schedule: Scheduler = "* 11 10 * * *".try_into().unwrap();
        let date = Utc.ymd(2010, 1, 1).and_hms(10, 10, 0);

        let expected_utc = Utc.ymd(2010, 1, 1).and_hms(10, 11, 0);

        let next = schedule.next(&date, Some(UTC)).unwrap();

        assert_eq!(next, expected_utc);
    }

    #[test]
    fn cron_should_be_time_zone_aware_with_custom_time_zone() {
        let mut schedule: Scheduler = "* 11 10 * * *".try_into().unwrap();

        let date = Utc.ymd(2010, 1, 1).and_hms(10, 10, 0);
        let expected_utc = Utc.ymd(2010, 1, 2).and_hms(09, 11, 0);

        let tz = chrono_tz::Europe::Rome;

        let next = schedule.next(&date, Some(tz)).unwrap();

        assert_eq!(next.with_timezone(&Utc), expected_utc);
    }
}