1#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::correctness)]
2use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveTime, Utc};
5use chrono_tz::Tz;
6
7mod types;
8
9pub use crate::types::{DayOfWeek, IntoCronValue};
10
11type Filter = Box<dyn Fn() -> bool + Send + Sync>;
12
13pub struct Cron {
15 expression: String,
16 timezone: Tz,
17 repeat_seconds: u32,
18 filters: Vec<Filter>,
19 reject_filters: Vec<Filter>,
20}
21
22impl Default for Cron {
23 fn default() -> Self {
24 Self::new()
25 }
26}
27
28impl Cron {
29 #[must_use]
31 pub fn new() -> Self {
32 Self {
33 expression: "* * * * *".to_string(),
34 timezone: Tz::UTC,
35 repeat_seconds: 0,
36 filters: Vec::new(),
37 reject_filters: Vec::new(),
38 }
39 }
40
41 #[must_use]
43 pub fn expression(&self) -> &str {
44 &self.expression
45 }
46
47 #[must_use]
51 pub const fn repeat_seconds(&self) -> u32 {
52 self.repeat_seconds
53 }
54
55 #[must_use]
57 pub fn filters_pass(&self) -> bool {
58 self.filters.iter().all(|f| f()) && !self.reject_filters.iter().any(|f| f())
59 }
60
61 pub fn cron(&mut self, expression: &str) -> &mut Self {
63 self.expression = expression.to_string();
64 self
65 }
66
67 pub fn when<F: Fn() -> bool + Send + Sync + 'static>(&mut self, filter: F) -> &mut Self {
69 self.filters.push(Box::new(filter));
70 self
71 }
72
73 pub fn skip<F: Fn() -> bool + Send + Sync + 'static>(&mut self, filter: F) -> &mut Self {
75 self.reject_filters.push(Box::new(filter));
76 self
77 }
78
79 pub fn between(&mut self, start_time: &str, end_time: &str) -> &mut Self {
84 let filter = self.in_time_interval(start_time, end_time);
85 self.filters.push(filter);
86 self
87 }
88
89 pub fn unless_between(&mut self, start_time: &str, end_time: &str) -> &mut Self {
93 let filter = self.in_time_interval(start_time, end_time);
94 self.reject_filters.push(filter);
95 self
96 }
97
98 pub fn every_second(&mut self) -> &mut Self {
100 self.repeat_every(1)
101 }
102
103 pub fn every_two_seconds(&mut self) -> &mut Self {
105 self.repeat_every(2)
106 }
107
108 pub fn every_five_seconds(&mut self) -> &mut Self {
110 self.repeat_every(5)
111 }
112
113 pub fn every_ten_seconds(&mut self) -> &mut Self {
115 self.repeat_every(10)
116 }
117
118 pub fn every_fifteen_seconds(&mut self) -> &mut Self {
120 self.repeat_every(15)
121 }
122
123 pub fn every_twenty_seconds(&mut self) -> &mut Self {
125 self.repeat_every(20)
126 }
127
128 pub fn every_thirty_seconds(&mut self) -> &mut Self {
130 self.repeat_every(30)
131 }
132
133 pub fn every_minute(&mut self) -> &mut Self {
135 self.splice_into_position(1, "*")
136 }
137
138 pub fn every_two_minutes(&mut self) -> &mut Self {
140 self.splice_into_position(1, "*/2")
141 }
142
143 pub fn every_three_minutes(&mut self) -> &mut Self {
145 self.splice_into_position(1, "*/3")
146 }
147
148 pub fn every_four_minutes(&mut self) -> &mut Self {
150 self.splice_into_position(1, "*/4")
151 }
152
153 pub fn every_five_minutes(&mut self) -> &mut Self {
155 self.splice_into_position(1, "*/5")
156 }
157
158 pub fn every_ten_minutes(&mut self) -> &mut Self {
160 self.splice_into_position(1, "*/10")
161 }
162
163 pub fn every_fifteen_minutes(&mut self) -> &mut Self {
165 self.splice_into_position(1, "*/15")
166 }
167
168 pub fn every_thirty_minutes(&mut self) -> &mut Self {
170 self.splice_into_position(1, "*/30")
171 }
172
173 pub fn hourly(&mut self) -> &mut Self {
175 self.splice_into_position(1, "0")
176 }
177
178 pub fn hourly_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
180 let s = offset.into_cron_value();
181 self.hour_based_schedule(&s, "*")
182 }
183
184 pub fn every_odd_hour(&mut self) -> &mut Self {
186 self.hour_based_schedule("0", "1-23/2")
187 }
188
189 pub fn every_odd_hour_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
191 let s = offset.into_cron_value();
192 self.hour_based_schedule(&s, "1-23/2")
193 }
194
195 pub fn every_two_hours(&mut self) -> &mut Self {
197 self.hour_based_schedule("0", "*/2")
198 }
199
200 pub fn every_two_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
202 let s = offset.into_cron_value();
203 self.hour_based_schedule(&s, "*/2")
204 }
205
206 pub fn every_three_hours(&mut self) -> &mut Self {
208 self.hour_based_schedule("0", "*/3")
209 }
210
211 pub fn every_three_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
213 let s = offset.into_cron_value();
214 self.hour_based_schedule(&s, "*/3")
215 }
216
217 pub fn every_four_hours(&mut self) -> &mut Self {
219 self.hour_based_schedule("0", "*/4")
220 }
221
222 pub fn every_four_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
224 let s = offset.into_cron_value();
225 self.hour_based_schedule(&s, "*/4")
226 }
227
228 pub fn every_six_hours(&mut self) -> &mut Self {
230 self.hour_based_schedule("0", "*/6")
231 }
232
233 pub fn every_six_hours_at(&mut self, offset: impl IntoCronValue) -> &mut Self {
235 let s = offset.into_cron_value();
236 self.hour_based_schedule(&s, "*/6")
237 }
238
239 pub fn daily(&mut self) -> &mut Self {
241 self.hour_based_schedule("0", "0")
242 }
243
244 pub fn at(&mut self, time: &str) -> &mut Self {
246 self.daily_at(time)
247 }
248
249 pub fn daily_at(&mut self, time: &str) -> &mut Self {
253 let segments: Vec<&str> = time.split(':').collect();
254 let hour: u32 = segments.first().and_then(|s| s.parse().ok()).unwrap_or(0);
255 let minute: u32 = segments.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
256 let hour_s = hour.to_string();
257 let minute_s = minute.to_string();
258 self.hour_based_schedule(&minute_s, &hour_s)
259 }
260
261 pub fn twice_daily(&mut self, first: u32, second: u32) -> &mut Self {
263 self.twice_daily_at(first, second, 0)
264 }
265
266 pub fn twice_daily_at(&mut self, first: u32, second: u32, offset: u32) -> &mut Self {
268 let hours = format!("{first},{second}");
269 let offset_s = offset.to_string();
270 self.hour_based_schedule(&offset_s, &hours)
271 }
272
273 pub fn weekdays(&mut self) -> &mut Self {
275 let s = format!("{}-{}", DayOfWeek::Monday as u32, DayOfWeek::Friday as u32);
276 self.days(s)
277 }
278
279 pub fn weekends(&mut self) -> &mut Self {
281 let s = format!(
282 "{},{}",
283 DayOfWeek::Saturday as u32,
284 DayOfWeek::Sunday as u32
285 );
286 self.days(s)
287 }
288
289 pub fn mondays(&mut self) -> &mut Self {
291 self.days(DayOfWeek::Monday)
292 }
293
294 pub fn tuesdays(&mut self) -> &mut Self {
296 self.days(DayOfWeek::Tuesday)
297 }
298
299 pub fn wednesdays(&mut self) -> &mut Self {
301 self.days(DayOfWeek::Wednesday)
302 }
303
304 pub fn thursdays(&mut self) -> &mut Self {
306 self.days(DayOfWeek::Thursday)
307 }
308
309 pub fn fridays(&mut self) -> &mut Self {
311 self.days(DayOfWeek::Friday)
312 }
313
314 pub fn saturdays(&mut self) -> &mut Self {
316 self.days(DayOfWeek::Saturday)
317 }
318
319 pub fn sundays(&mut self) -> &mut Self {
321 self.days(DayOfWeek::Sunday)
322 }
323
324 pub fn weekly(&mut self) -> &mut Self {
326 self.splice_into_position(1, "0");
327 self.splice_into_position(2, "0");
328 self.splice_into_position(5, "0")
329 }
330
331 pub fn weekly_on(&mut self, day_of_week: impl IntoCronValue, time: &str) -> &mut Self {
333 self.daily_at(time);
334 self.days(day_of_week)
335 }
336
337 pub fn monthly(&mut self) -> &mut Self {
339 self.splice_into_position(1, "0");
340 self.splice_into_position(2, "0");
341 self.splice_into_position(3, "1")
342 }
343
344 pub fn monthly_on(&mut self, day_of_month: u32, time: &str) -> &mut Self {
346 self.daily_at(time);
347 let s = day_of_month.to_string();
348 self.splice_into_position(3, &s)
349 }
350
351 pub fn twice_monthly(&mut self, first: u32, second: u32) -> &mut Self {
353 self.twice_monthly_at(first, second, "0:0")
354 }
355
356 pub fn twice_monthly_at(&mut self, first: u32, second: u32, time: &str) -> &mut Self {
358 let days = format!("{first},{second}");
359 self.daily_at(time);
360 self.splice_into_position(3, &days)
361 }
362
363 pub fn last_day_of_month(&mut self) -> &mut Self {
368 self.last_day_of_month_at("0:0")
369 }
370
371 pub fn last_day_of_month_at(&mut self, time: &str) -> &mut Self {
375 self.daily_at(time);
376 let now = current_time(self.timezone);
377 let last = last_day_of(now.year(), now.month());
378 let s = last.to_string();
379 self.splice_into_position(3, &s)
380 }
381
382 pub fn days_of_month(&mut self, days: &[u32]) -> &mut Self {
384 self.daily_at("0:0");
385 let s = days
386 .iter()
387 .map(ToString::to_string)
388 .collect::<Vec<_>>()
389 .join(",");
390 self.splice_into_position(3, &s)
391 }
392
393 pub fn quarterly(&mut self) -> &mut Self {
395 self.splice_into_position(1, "0");
396 self.splice_into_position(2, "0");
397 self.splice_into_position(3, "1");
398 self.splice_into_position(4, "1-12/3")
399 }
400
401 pub fn quarterly_on(&mut self, day_of_quarter: u32, time: &str) -> &mut Self {
403 self.daily_at(time);
404 let s = day_of_quarter.to_string();
405 self.splice_into_position(3, &s);
406 self.splice_into_position(4, "1-12/3")
407 }
408
409 pub fn yearly(&mut self) -> &mut Self {
411 self.splice_into_position(1, "0");
412 self.splice_into_position(2, "0");
413 self.splice_into_position(3, "1");
414 self.splice_into_position(4, "1")
415 }
416
417 pub fn yearly_on(
419 &mut self,
420 month: u32,
421 day_of_month: impl IntoCronValue,
422 time: &str,
423 ) -> &mut Self {
424 self.daily_at(time);
425 let m = month.to_string();
426 let d = day_of_month.into_cron_value();
427 self.splice_into_position(3, &d);
428 self.splice_into_position(4, &m)
429 }
430
431 pub fn days(&mut self, days: impl IntoCronValue) -> &mut Self {
433 let s = days.into_cron_value();
434 self.splice_into_position(5, &s)
435 }
436
437 pub const fn timezone(&mut self, timezone: Tz) -> &mut Self {
440 self.timezone = timezone;
441 self
442 }
443}
444
445impl Cron {
446 fn in_time_interval(&self, start_time: &str, end_time: &str) -> Filter {
447 let tz = self.timezone;
448 let start = parse_time_of_day(start_time);
449 let end = parse_time_of_day(end_time);
450
451 Box::new(move || {
452 let now = current_time(tz);
453 let today = now.date_naive();
454 let Some(mut start_dt) = today.and_time(start).and_local_timezone(tz).single() else {
455 return false;
456 };
457 let Some(mut end_dt) = today.and_time(end).and_local_timezone(tz).single() else {
458 return false;
459 };
460
461 if end_dt < start_dt {
462 if start_dt > now {
463 start_dt -= Duration::days(1);
464 } else {
465 end_dt += Duration::days(1);
466 }
467 }
468
469 now >= start_dt && now <= end_dt
470 })
471 }
472
473 fn repeat_every(&mut self, seconds: u32) -> &mut Self {
474 assert!(
475 seconds > 0,
476 "The seconds [{seconds}] must be greater than zero."
477 );
478 assert!(
479 60 % seconds == 0,
480 "The seconds [{seconds}] are not evenly divisible by 60."
481 );
482 self.repeat_seconds = seconds;
483 self.every_minute()
484 }
485
486 fn hour_based_schedule(&mut self, minutes: &str, hours: &str) -> &mut Self {
487 self.splice_into_position(1, minutes);
488 self.splice_into_position(2, hours)
489 }
490
491 fn splice_into_position(&mut self, position: usize, value: &str) -> &mut Self {
492 let mut segments: Vec<String> = self
493 .expression
494 .split_whitespace()
495 .map(ToString::to_string)
496 .collect();
497 while segments.len() < position {
498 segments.push("*".to_string());
499 }
500 segments[position - 1] = value.to_string();
501 self.expression = segments.join(" ");
502 self
503 }
504}
505
506fn parse_time_of_day(time: &str) -> NaiveTime {
507 let parts: Vec<&str> = time.split(':').collect();
508 let h: u32 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
509 let m: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
510 let s: u32 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
511 NaiveTime::from_hms_opt(h, m, s).unwrap_or(NaiveTime::MIN)
512}
513
514fn last_day_of(year: i32, month: u32) -> u32 {
515 let (y, m) = if month == 12 {
516 (year + 1, 1)
517 } else {
518 (year, month + 1)
519 };
520 let first_of_next = NaiveDate::from_ymd_opt(y, m, 1).unwrap();
521 let last = first_of_next - Duration::days(1);
522 last.day()
523}
524
525#[cfg(test)]
526thread_local! {
527 static TEST_NOW: std::cell::Cell<Option<DateTime<Utc>>> =
528 const { std::cell::Cell::new(None) };
529}
530
531fn current_time(tz: Tz) -> DateTime<Tz> {
532 #[cfg(test)]
533 if let Some(t) = TEST_NOW.with(std::cell::Cell::get) {
534 return t.with_timezone(&tz);
535 }
536
537 Utc::now().with_timezone(&tz)
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543 use chrono::TimeZone;
544
545 #[must_use = "the guard restores the previous test-now on drop; bind it to a variable"]
546 struct TestNowGuard(Option<DateTime<Utc>>);
547
548 impl Drop for TestNowGuard {
549 fn drop(&mut self) {
550 TEST_NOW.with(|c| c.set(self.0));
551 }
552 }
553
554 fn set_test_now(now: DateTime<Utc>) -> TestNowGuard {
555 let prev = TEST_NOW.with(|c| c.replace(Some(now)));
556 TestNowGuard(prev)
557 }
558
559 fn event() -> Cron {
560 Cron::new()
561 }
562
563 #[test]
564 fn every_minute() {
565 let mut e = event();
566 assert_eq!("* * * * *", e.expression());
567 assert_eq!("* * * * *", e.every_minute().expression());
568 }
569
570 #[test]
571 fn every_x_minutes() {
572 let mut e = event();
573 assert_eq!("*/2 * * * *", e.every_two_minutes().expression());
574 assert_eq!("*/3 * * * *", e.every_three_minutes().expression());
575 assert_eq!("*/4 * * * *", e.every_four_minutes().expression());
576 assert_eq!("*/5 * * * *", e.every_five_minutes().expression());
577 assert_eq!("*/10 * * * *", e.every_ten_minutes().expression());
578 assert_eq!("*/15 * * * *", e.every_fifteen_minutes().expression());
579 assert_eq!("*/30 * * * *", e.every_thirty_minutes().expression());
580 }
581
582 #[test]
583 fn daily() {
584 let mut e = event();
585 assert_eq!("0 0 * * *", e.daily().expression());
586 }
587
588 #[test]
589 fn daily_at() {
590 let mut e = event();
591 assert_eq!("8 13 * * *", e.daily_at("13:08").expression());
592 }
593
594 #[test]
595 fn daily_at_parses_minutes_and_ignores_seconds_when_seconds_are_defined() {
596 let mut e = event();
597 assert_eq!("8 13 * * *", e.daily_at("13:08:10").expression());
598 }
599
600 #[test]
601 fn twice_daily() {
602 let mut e = event();
603 assert_eq!("0 3,15 * * *", e.twice_daily(3, 15).expression());
604 }
605
606 #[test]
607 fn twice_daily_at() {
608 let mut e = event();
609 assert_eq!("5 3,15 * * *", e.twice_daily_at(3, 15, 5).expression());
610 }
611
612 #[test]
613 fn weekly() {
614 let mut e = event();
615 assert_eq!("0 0 * * 0", e.weekly().expression());
616 }
617
618 #[test]
619 fn weekly_on() {
620 let mut e = event();
621 assert_eq!("0 8 * * 1", e.weekly_on(1u32, "8:00").expression());
622 }
623
624 #[test]
625 fn override_with_hourly() {
626 let mut e = event();
627 assert_eq!("0 * * * *", e.every_five_minutes().hourly().expression());
628 assert_eq!("37 * * * *", e.hourly_at(37).expression());
629 assert_eq!("*/10 * * * *", e.hourly_at("*/10").expression());
630 assert_eq!("15,30,45 * * * *", e.hourly_at([15, 30, 45]).expression());
631 }
632
633 #[test]
634 fn hourly() {
635 let mut e = event();
636 assert_eq!("0 1-23/2 * * *", e.every_odd_hour().expression());
637 assert_eq!("0 */2 * * *", e.every_two_hours().expression());
638 assert_eq!("0 */3 * * *", e.every_three_hours().expression());
639 assert_eq!("0 */4 * * *", e.every_four_hours().expression());
640 assert_eq!("0 */6 * * *", e.every_six_hours().expression());
641
642 assert_eq!("37 1-23/2 * * *", e.every_odd_hour_at(37).expression());
643 assert_eq!("37 */2 * * *", e.every_two_hours_at(37).expression());
644 assert_eq!("37 */3 * * *", e.every_three_hours_at(37).expression());
645 assert_eq!("37 */4 * * *", e.every_four_hours_at(37).expression());
646 assert_eq!("37 */6 * * *", e.every_six_hours_at(37).expression());
647
648 assert_eq!(
649 "*/10 1-23/2 * * *",
650 e.every_odd_hour_at("*/10").expression()
651 );
652 assert_eq!("*/10 */2 * * *", e.every_two_hours_at("*/10").expression());
653 assert_eq!(
654 "*/10 */3 * * *",
655 e.every_three_hours_at("*/10").expression()
656 );
657 assert_eq!("*/10 */4 * * *", e.every_four_hours_at("*/10").expression());
658 assert_eq!("*/10 */6 * * *", e.every_six_hours_at("*/10").expression());
659
660 assert_eq!(
661 "15,30,45 1-23/2 * * *",
662 e.every_odd_hour_at([15, 30, 45]).expression()
663 );
664 assert_eq!(
665 "15,30,45 */2 * * *",
666 e.every_two_hours_at([15, 30, 45]).expression()
667 );
668 assert_eq!(
669 "15,30,45 */3 * * *",
670 e.every_three_hours_at([15, 30, 45]).expression()
671 );
672 assert_eq!(
673 "15,30,45 */4 * * *",
674 e.every_four_hours_at([15, 30, 45]).expression()
675 );
676 assert_eq!(
677 "15,30,45 */6 * * *",
678 e.every_six_hours_at([15, 30, 45]).expression()
679 );
680 }
681
682 #[test]
683 fn monthly() {
684 let mut e = event();
685 assert_eq!("0 0 1 * *", e.monthly().expression());
686 }
687
688 #[test]
689 fn monthly_on() {
690 let mut e = event();
691 assert_eq!("0 15 4 * *", e.monthly_on(4, "15:00").expression());
692 }
693
694 #[test]
695 fn last_day_of_month() {
696 let _g = set_test_now(Utc.with_ymd_and_hms(2020, 10, 10, 10, 10, 10).unwrap());
697 let mut e = event();
698 assert_eq!("0 0 31 * *", e.last_day_of_month().expression());
699 }
700
701 #[test]
702 fn twice_monthly() {
703 let mut e = event();
704 assert_eq!("0 0 1,16 * *", e.twice_monthly(1, 16).expression());
705 }
706
707 #[test]
708 fn twice_monthly_at_time() {
709 let mut e = event();
710 assert_eq!(
711 "30 1 1,16 * *",
712 e.twice_monthly_at(1, 16, "1:30").expression()
713 );
714 }
715
716 #[test]
717 fn monthly_on_with_minutes() {
718 let mut e = event();
719 assert_eq!("15 15 4 * *", e.monthly_on(4, "15:15").expression());
720 }
721
722 #[test]
723 fn weekdays_daily() {
724 let mut e = event();
725 assert_eq!("0 0 * * 1-5", e.weekdays().daily().expression());
726 }
727
728 #[test]
729 fn weekdays_hourly() {
730 let mut e = event();
731 assert_eq!("0 * * * 1-5", e.weekdays().hourly().expression());
732 }
733
734 #[test]
735 fn weekdays() {
736 let mut e = event();
737 assert_eq!("* * * * 1-5", e.weekdays().expression());
738 }
739
740 #[test]
741 fn weekends() {
742 let mut e = event();
743 assert_eq!("* * * * 6,0", e.weekends().expression());
744 }
745
746 #[test]
747 fn sundays() {
748 let mut e = event();
749 assert_eq!("* * * * 0", e.sundays().expression());
750 }
751
752 #[test]
753 fn mondays() {
754 let mut e = event();
755 assert_eq!("* * * * 1", e.mondays().expression());
756 }
757
758 #[test]
759 fn tuesdays() {
760 let mut e = event();
761 assert_eq!("* * * * 2", e.tuesdays().expression());
762 }
763
764 #[test]
765 fn wednesdays() {
766 let mut e = event();
767 assert_eq!("* * * * 3", e.wednesdays().expression());
768 }
769
770 #[test]
771 fn thursdays() {
772 let mut e = event();
773 assert_eq!("* * * * 4", e.thursdays().expression());
774 }
775
776 #[test]
777 fn fridays() {
778 let mut e = event();
779 assert_eq!("* * * * 5", e.fridays().expression());
780 }
781
782 #[test]
783 fn saturdays() {
784 let mut e = event();
785 assert_eq!("* * * * 6", e.saturdays().expression());
786 }
787
788 #[test]
789 fn quarterly() {
790 let mut e = event();
791 assert_eq!("0 0 1 1-12/3 *", e.quarterly().expression());
792 }
793
794 #[test]
795 fn yearly() {
796 let mut e = event();
797 assert_eq!("0 0 1 1 *", e.yearly().expression());
798 }
799
800 #[test]
801 fn yearly_on() {
802 let mut e = event();
803 assert_eq!("8 15 5 4 *", e.yearly_on(4, 5u32, "15:08").expression());
804 }
805
806 #[test]
807 fn yearly_on_mondays_only() {
808 let mut e = event();
809 assert_eq!(
810 "1 9 * 7 1",
811 e.mondays().yearly_on(7, "*", "09:01").expression()
812 );
813 }
814
815 #[test]
816 fn yearly_on_tuesdays_and_day_of_month_20() {
817 let mut e = event();
818 assert_eq!(
819 "1 9 20 7 2",
820 e.tuesdays().yearly_on(7, 20u32, "09:01").expression()
821 );
822 }
823}