forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

cron.rs59 lines, 2.1 KiBHistoryRawDownload
1//! Standard 5-field cron expressions in UTC, for `[on] schedule`.
2//!
3//! Times are Unix seconds. The functions are pure, so the scheduler's tick logic can be tested
4//! with a fake clock.
5
6use chrono::DateTime;
7use croner::Cron;
8
9/// Parses a 5-field cron expression (`minute hour day-of-month month day-of-week`).
10pub fn parse(expr: &str) -> Result<Cron, String> {
11 let trimmed = expr.trim();
12 if trimmed.split_whitespace().count() != 5 {
13 return Err(
14 "must have exactly 5 fields: minute hour day-of-month month day-of-week".into(),
15 );
16 }
17 trimmed.parse::<Cron>().map_err(|e| e.to_string())
18}
19
20/// The first time strictly after `after` that `cron` matches.
21fn next_one(cron: &Cron, after: i64) -> Option<i64> {
22 let start = DateTime::from_timestamp(after, 0)?.naive_utc();
23 let next = cron.find_next_occurrence(&start, false).ok()?;
24 Some(next.and_utc().timestamp())
25}
26
27/// The first time strictly after `after` that any of `exprs` matches. Expressions that do not
28/// parse are ignored.
29pub fn next_after<S: AsRef<str>>(exprs: &[S], after: i64) -> Option<i64> {
30 exprs
31 .iter()
32 .filter_map(|e| parse(e.as_ref()).ok())
33 .filter_map(|c| next_one(&c, after))
34 .min()
35}
36
37/// Whether any of `exprs` matched a time `t` with `last < t <= now`. However many ticks fell in
38/// that window, the answer is one yes: a scheduler that was down catches up once.
39pub fn fired_between<S: AsRef<str>>(exprs: &[S], last: i64, now: i64) -> bool {
40 next_after(exprs, last).is_some_and(|t| t <= now)
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 // 2026-10-15 12:00:00 UTC
48 const NOON: i64 = 1_791_979_200;
49
50 #[test]
51 fn fires_inside_the_window_only() {
52 assert!(fired_between(&["30 12 * * *"], NOON, NOON + 1800));
53 assert!(!fired_between(&["30 12 * * *"], NOON, NOON + 1799));
54 // The window is open at `last`: a tick already handled does not fire again.
55 assert!(!fired_between(&["0 12 * * *"], NOON, NOON + 60));
56 // A week of downtime is still one yes.
57 assert!(fired_between(&["* * * * *"], NOON, NOON + 7 * 86_400));
58 }
59}