#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::correctness)]
use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveTime, Utc};
use chrono_tz::Tz;
mod types;
pub use crate::types::{DayOfWeek, IntoCronValue};
type Filter = Box<dyn Fn() -> bool + Send + Sync>;
pub struct Cron {
expression: String,
timezone: Tz,
repeat_seconds: u32,
filters: Vec<Filter>,
reject_filters: Vec<Filter>,
}
impl Default for Cron {
fn default() -> Self {
Self::new()
}
}
impl Cron {
#[must_use]
pub fn new() -> Self {
Self {
expression: "* * * * *".to_string(),
timezone: Tz::UTC,
repeat_seconds: 0,
filters: Vec::new(),
reject_filters: Vec::new(),
}
}
#[must_use]
pub fn expression(&self) -> &str {
&self.expression
}
#[must_use]
pub const fn repeat_seconds(&self) -> u32 {
self.repeat_seconds
}
#[must_use]
pub fn filters_pass(&self) -> bool {
self.filters.iter().all(|f| f()) && !self.reject_filters.iter().any(|f| f())
}
pub fn cron(&mut self, expression: &str) -> &mut Self {
self.expression = expression.to_string();
self
}
pub fn when<F: Fn() -> bool + Send + Sync + 'static>(&mut self, filter: F) -> &mut Self {
self.filters.push(Box::new(filter));
self
}
pub fn skip<F: Fn() -> bool + Send + Sync + 'static>(&mut self, filter: F) -> &mut Self {
self.reject_filters.push(Box::new(filter));
self
}
pub fn between(&mut self, start_time: &str, end_time: &str) -> &mut Self {
let filter = self.in_time_interval(start_time, end_time);
self.filters.push(filter);
self
}
pub fn unless_between(&mut self, start_time: &str, end_time: &str) -> &mut Self {
let filter = self.in_time_interval(start_time, end_time);
self.reject_filters.push(filter);
self
}
pub fn every_second(&mut self) -> &mut Self {
self.repeat_every(1)
}
pub fn every_two_seconds(&mut self) -> &mut Self {
self.repeat_every(2)
}
pub fn every_five_seconds(&mut self) -> &mut Self {
self.repeat_every(5)
}
pub fn every_ten_seconds(&mut self) -> &mut Self {
self.repeat_every(10)
}
pub fn every_fifteen_seconds(&mut self) -> &mut Self {
self.repeat_every(15)
}
pub fn every_twenty_seconds(&mut self) -> &mut Self {
self.repeat_every(20)
}
pub fn every_thirty_seconds(&mut self) -> &mut Self {
self.repeat_every(30)
}
pub fn every_minute(&mut self) -> &mut Self {
self.splice_into_position(1, "*")
}
pub fn every_two_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/2")
}
pub fn every_three_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/3")
}
pub fn every_four_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/4")
}
pub fn every_five_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/5")
}
pub fn every_ten_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/10")
}
pub fn every_fifteen_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/15")
}
pub fn every_thirty_minutes(&mut self) -> &mut Self {
self.splice_into_position(1, "*/30")
}
pub fn hourly(&mut self) -> &mut Self {
self.splice_into_position(1, "0")
}
pub fn hourly_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
let s = offset.into_cron_value();
self.hour_based_schedule(&s, "*")
}
pub fn every_odd_hour(&mut self) -> &mut Self {
self.hour_based_schedule("0", "1-23/2")
}
pub fn every_odd_hour_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
let s = offset.into_cron_value();
self.hour_based_schedule(&s, "1-23/2")
}
pub fn every_two_hours(&mut self) -> &mut Self {
self.hour_based_schedule("0", "*/2")
}
pub fn every_two_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
let s = offset.into_cron_value();
self.hour_based_schedule(&s, "*/2")
}
pub fn every_three_hours(&mut self) -> &mut Self {
self.hour_based_schedule("0", "*/3")
}
pub fn every_three_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
let s = offset.into_cron_value();
self.hour_based_schedule(&s, "*/3")
}
pub fn every_four_hours(&mut self) -> &mut Self {
self.hour_based_schedule("0", "*/4")
}
pub fn every_four_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
let s = offset.into_cron_value();
self.hour_based_schedule(&s, "*/4")
}
pub fn every_six_hours(&mut self) -> &mut Self {
self.hour_based_schedule("0", "*/6")
}
pub fn every_six_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
let s = offset.into_cron_value();
self.hour_based_schedule(&s, "*/6")
}
pub fn daily(&mut self) -> &mut Self {
self.hour_based_schedule("0", "0")
}
pub fn at(&mut self, time: &str) -> &mut Self {
self.daily_at(time)
}
pub fn daily_at(&mut self, time: &str) -> &mut Self {
let segments: Vec<&str> = time.split(':').collect();
let hour: u32 = segments.first().and_then(|s| s.parse().ok()).unwrap_or(0);
let minute: u32 = segments.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
let hour_s = hour.to_string();
let minute_s = minute.to_string();
self.hour_based_schedule(&minute_s, &hour_s)
}
pub fn twice_daily(&mut self, first: u32, second: u32) -> &mut Self {
self.twice_daily_at(first, second, 0)
}
pub fn twice_daily_at(&mut self, first: u32, second: u32, offset: u32) -> &mut Self {
let hours = format!("{first},{second}");
let offset_s = offset.to_string();
self.hour_based_schedule(&offset_s, &hours)
}
pub fn weekdays(&mut self) -> &mut Self {
let s = format!("{}-{}", DayOfWeek::Monday as u32, DayOfWeek::Friday as u32);
self.days(s)
}
pub fn weekends(&mut self) -> &mut Self {
let s = format!(
"{},{}",
DayOfWeek::Saturday as u32,
DayOfWeek::Sunday as u32
);
self.days(s)
}
pub fn mondays(&mut self) -> &mut Self {
self.days(DayOfWeek::Monday)
}
pub fn tuesdays(&mut self) -> &mut Self {
self.days(DayOfWeek::Tuesday)
}
pub fn wednesdays(&mut self) -> &mut Self {
self.days(DayOfWeek::Wednesday)
}
pub fn thursdays(&mut self) -> &mut Self {
self.days(DayOfWeek::Thursday)
}
pub fn fridays(&mut self) -> &mut Self {
self.days(DayOfWeek::Friday)
}
pub fn saturdays(&mut self) -> &mut Self {
self.days(DayOfWeek::Saturday)
}
pub fn sundays(&mut self) -> &mut Self {
self.days(DayOfWeek::Sunday)
}
pub fn weekly(&mut self) -> &mut Self {
self.splice_into_position(1, "0");
self.splice_into_position(2, "0");
self.splice_into_position(5, "0")
}
pub fn weekly_on(&mut self, day_of_week: impl IntoCronValue, time: &str) -> &mut Self {
self.daily_at(time);
self.days(day_of_week)
}
pub fn monthly(&mut self) -> &mut Self {
self.splice_into_position(1, "0");
self.splice_into_position(2, "0");
self.splice_into_position(3, "1")
}
pub fn monthly_on(&mut self, day_of_month: u32, time: &str) -> &mut Self {
self.daily_at(time);
let s = day_of_month.to_string();
self.splice_into_position(3, &s)
}
pub fn twice_monthly(&mut self, first: u32, second: u32) -> &mut Self {
self.twice_monthly_at(first, second, "0:0")
}
pub fn twice_monthly_at(&mut self, first: u32, second: u32, time: &str) -> &mut Self {
let days = format!("{first},{second}");
self.daily_at(time);
self.splice_into_position(3, &days)
}
pub fn last_day_of_month(&mut self) -> &mut Self {
self.last_day_of_month_at("0:0")
}
pub fn last_day_of_month_at(&mut self, time: &str) -> &mut Self {
self.daily_at(time);
let now = current_time(self.timezone);
let last = last_day_of(now.year(), now.month());
let s = last.to_string();
self.splice_into_position(3, &s)
}
pub fn days_of_month(&mut self, days: &[u32]) -> &mut Self {
self.daily_at("0:0");
let s = days
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",");
self.splice_into_position(3, &s)
}
pub fn quarterly(&mut self) -> &mut Self {
self.splice_into_position(1, "0");
self.splice_into_position(2, "0");
self.splice_into_position(3, "1");
self.splice_into_position(4, "1-12/3")
}
pub fn quarterly_on(&mut self, day_of_quarter: u32, time: &str) -> &mut Self {
self.daily_at(time);
let s = day_of_quarter.to_string();
self.splice_into_position(3, &s);
self.splice_into_position(4, "1-12/3")
}
pub fn yearly(&mut self) -> &mut Self {
self.splice_into_position(1, "0");
self.splice_into_position(2, "0");
self.splice_into_position(3, "1");
self.splice_into_position(4, "1")
}
pub fn yearly_on(
&mut self,
month: u32,
day_of_month: impl IntoCronValue,
time: &str,
) -> &mut Self {
self.daily_at(time);
let m = month.to_string();
let d = day_of_month.into_cron_value();
self.splice_into_position(3, &d);
self.splice_into_position(4, &m)
}
pub fn days(&mut self, days: impl IntoCronValue) -> &mut Self {
let s = days.into_cron_value();
self.splice_into_position(5, &s)
}
pub const fn timezone(&mut self, timezone: Tz) -> &mut Self {
self.timezone = timezone;
self
}
}
impl Cron {
fn in_time_interval(&self, start_time: &str, end_time: &str) -> Filter {
let tz = self.timezone;
let start = parse_time_of_day(start_time);
let end = parse_time_of_day(end_time);
Box::new(move || {
let now = current_time(tz);
let today = now.date_naive();
let Some(mut start_dt) = today.and_time(start).and_local_timezone(tz).single() else {
return false;
};
let Some(mut end_dt) = today.and_time(end).and_local_timezone(tz).single() else {
return false;
};
if end_dt < start_dt {
if start_dt > now {
start_dt -= Duration::days(1);
} else {
end_dt += Duration::days(1);
}
}
now >= start_dt && now <= end_dt
})
}
fn repeat_every(&mut self, seconds: u32) -> &mut Self {
assert!(
seconds > 0,
"The seconds [{seconds}] must be greater than zero."
);
assert!(
60 % seconds == 0,
"The seconds [{seconds}] are not evenly divisible by 60."
);
self.repeat_seconds = seconds;
self.every_minute()
}
fn hour_based_schedule(&mut self, minutes: &str, hours: &str) -> &mut Self {
self.splice_into_position(1, minutes);
self.splice_into_position(2, hours)
}
fn splice_into_position(&mut self, position: usize, value: &str) -> &mut Self {
let mut segments: Vec<String> = self
.expression
.split_whitespace()
.map(ToString::to_string)
.collect();
while segments.len() < position {
segments.push("*".to_string());
}
segments[position - 1] = value.to_string();
self.expression = segments.join(" ");
self
}
}
fn parse_time_of_day(time: &str) -> NaiveTime {
let parts: Vec<&str> = time.split(':').collect();
let h: u32 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
let m: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
let s: u32 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
NaiveTime::from_hms_opt(h, m, s).unwrap_or(NaiveTime::MIN)
}
fn last_day_of(year: i32, month: u32) -> u32 {
let (y, m) = if month == 12 {
(year + 1, 1)
} else {
(year, month + 1)
};
let first_of_next = NaiveDate::from_ymd_opt(y, m, 1).unwrap();
let last = first_of_next - Duration::days(1);
last.day()
}
#[cfg(test)]
thread_local! {
static TEST_NOW: std::cell::Cell<Option<DateTime<Utc>>> =
const { std::cell::Cell::new(None) };
}
fn current_time(tz: Tz) -> DateTime<Tz> {
#[cfg(test)]
if let Some(t) = TEST_NOW.with(std::cell::Cell::get) {
return t.with_timezone(&tz);
}
Utc::now().with_timezone(&tz)
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[must_use = "the guard restores the previous test-now on drop; bind it to a variable"]
struct TestNowGuard(Option<DateTime<Utc>>);
impl Drop for TestNowGuard {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(self.0));
}
}
fn set_test_now(now: DateTime<Utc>) -> TestNowGuard {
let prev = TEST_NOW.with(|c| c.replace(Some(now)));
TestNowGuard(prev)
}
fn event() -> Cron {
Cron::new()
}
#[test]
fn every_minute() {
let mut e = event();
assert_eq!("* * * * *", e.expression());
assert_eq!("* * * * *", e.every_minute().expression());
}
#[test]
fn every_x_minutes() {
let mut e = event();
assert_eq!("*/2 * * * *", e.every_two_minutes().expression());
assert_eq!("*/3 * * * *", e.every_three_minutes().expression());
assert_eq!("*/4 * * * *", e.every_four_minutes().expression());
assert_eq!("*/5 * * * *", e.every_five_minutes().expression());
assert_eq!("*/10 * * * *", e.every_ten_minutes().expression());
assert_eq!("*/15 * * * *", e.every_fifteen_minutes().expression());
assert_eq!("*/30 * * * *", e.every_thirty_minutes().expression());
}
#[test]
fn daily() {
let mut e = event();
assert_eq!("0 0 * * *", e.daily().expression());
}
#[test]
fn daily_at() {
let mut e = event();
assert_eq!("8 13 * * *", e.daily_at("13:08").expression());
}
#[test]
fn daily_at_parses_minutes_and_ignores_seconds_when_seconds_are_defined() {
let mut e = event();
assert_eq!("8 13 * * *", e.daily_at("13:08:10").expression());
}
#[test]
fn twice_daily() {
let mut e = event();
assert_eq!("0 3,15 * * *", e.twice_daily(3, 15).expression());
}
#[test]
fn twice_daily_at() {
let mut e = event();
assert_eq!("5 3,15 * * *", e.twice_daily_at(3, 15, 5).expression());
}
#[test]
fn weekly() {
let mut e = event();
assert_eq!("0 0 * * 0", e.weekly().expression());
}
#[test]
fn weekly_on() {
let mut e = event();
assert_eq!("0 8 * * 1", e.weekly_on(1u32, "8:00").expression());
}
#[test]
fn override_with_hourly() {
let mut e = event();
assert_eq!("0 * * * *", e.every_five_minutes().hourly().expression());
assert_eq!("37 * * * *", e.hourly_at(37).expression());
assert_eq!("*/10 * * * *", e.hourly_at("*/10").expression());
assert_eq!("15,30,45 * * * *", e.hourly_at([15, 30, 45]).expression());
}
#[test]
fn hourly() {
let mut e = event();
assert_eq!("0 1-23/2 * * *", e.every_odd_hour().expression());
assert_eq!("0 */2 * * *", e.every_two_hours().expression());
assert_eq!("0 */3 * * *", e.every_three_hours().expression());
assert_eq!("0 */4 * * *", e.every_four_hours().expression());
assert_eq!("0 */6 * * *", e.every_six_hours().expression());
assert_eq!("37 1-23/2 * * *", e.every_odd_hour_at(37).expression());
assert_eq!("37 */2 * * *", e.every_two_hours_at(37).expression());
assert_eq!("37 */3 * * *", e.every_three_hours_at(37).expression());
assert_eq!("37 */4 * * *", e.every_four_hours_at(37).expression());
assert_eq!("37 */6 * * *", e.every_six_hours_at(37).expression());
assert_eq!(
"*/10 1-23/2 * * *",
e.every_odd_hour_at("*/10").expression()
);
assert_eq!("*/10 */2 * * *", e.every_two_hours_at("*/10").expression());
assert_eq!(
"*/10 */3 * * *",
e.every_three_hours_at("*/10").expression()
);
assert_eq!("*/10 */4 * * *", e.every_four_hours_at("*/10").expression());
assert_eq!("*/10 */6 * * *", e.every_six_hours_at("*/10").expression());
assert_eq!(
"15,30,45 1-23/2 * * *",
e.every_odd_hour_at([15, 30, 45]).expression()
);
assert_eq!(
"15,30,45 */2 * * *",
e.every_two_hours_at([15, 30, 45]).expression()
);
assert_eq!(
"15,30,45 */3 * * *",
e.every_three_hours_at([15, 30, 45]).expression()
);
assert_eq!(
"15,30,45 */4 * * *",
e.every_four_hours_at([15, 30, 45]).expression()
);
assert_eq!(
"15,30,45 */6 * * *",
e.every_six_hours_at([15, 30, 45]).expression()
);
}
#[test]
fn monthly() {
let mut e = event();
assert_eq!("0 0 1 * *", e.monthly().expression());
}
#[test]
fn monthly_on() {
let mut e = event();
assert_eq!("0 15 4 * *", e.monthly_on(4, "15:00").expression());
}
#[test]
fn last_day_of_month() {
let _g = set_test_now(Utc.with_ymd_and_hms(2020, 10, 10, 10, 10, 10).unwrap());
let mut e = event();
assert_eq!("0 0 31 * *", e.last_day_of_month().expression());
}
#[test]
fn twice_monthly() {
let mut e = event();
assert_eq!("0 0 1,16 * *", e.twice_monthly(1, 16).expression());
}
#[test]
fn twice_monthly_at_time() {
let mut e = event();
assert_eq!(
"30 1 1,16 * *",
e.twice_monthly_at(1, 16, "1:30").expression()
);
}
#[test]
fn monthly_on_with_minutes() {
let mut e = event();
assert_eq!("15 15 4 * *", e.monthly_on(4, "15:15").expression());
}
#[test]
fn weekdays_daily() {
let mut e = event();
assert_eq!("0 0 * * 1-5", e.weekdays().daily().expression());
}
#[test]
fn weekdays_hourly() {
let mut e = event();
assert_eq!("0 * * * 1-5", e.weekdays().hourly().expression());
}
#[test]
fn weekdays() {
let mut e = event();
assert_eq!("* * * * 1-5", e.weekdays().expression());
}
#[test]
fn weekends() {
let mut e = event();
assert_eq!("* * * * 6,0", e.weekends().expression());
}
#[test]
fn sundays() {
let mut e = event();
assert_eq!("* * * * 0", e.sundays().expression());
}
#[test]
fn mondays() {
let mut e = event();
assert_eq!("* * * * 1", e.mondays().expression());
}
#[test]
fn tuesdays() {
let mut e = event();
assert_eq!("* * * * 2", e.tuesdays().expression());
}
#[test]
fn wednesdays() {
let mut e = event();
assert_eq!("* * * * 3", e.wednesdays().expression());
}
#[test]
fn thursdays() {
let mut e = event();
assert_eq!("* * * * 4", e.thursdays().expression());
}
#[test]
fn fridays() {
let mut e = event();
assert_eq!("* * * * 5", e.fridays().expression());
}
#[test]
fn saturdays() {
let mut e = event();
assert_eq!("* * * * 6", e.saturdays().expression());
}
#[test]
fn quarterly() {
let mut e = event();
assert_eq!("0 0 1 1-12/3 *", e.quarterly().expression());
}
#[test]
fn yearly() {
let mut e = event();
assert_eq!("0 0 1 1 *", e.yearly().expression());
}
#[test]
fn yearly_on() {
let mut e = event();
assert_eq!("8 15 5 4 *", e.yearly_on(4, 5u32, "15:08").expression());
}
#[test]
fn yearly_on_mondays_only() {
let mut e = event();
assert_eq!(
"1 9 * 7 1",
e.mondays().yearly_on(7, "*", "09:01").expression()
);
}
#[test]
fn yearly_on_tuesdays_and_day_of_month_20() {
let mut e = event();
assert_eq!(
"1 9 20 7 2",
e.tuesdays().yearly_on(7, 20u32, "09:01").expression()
);
}
}