hron 1.0.0

Human-readable cron — scheduling expressions that are a superset of what cron can express
Documentation
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A parsed hron schedule: expression + optional modifiers.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Schedule {
    pub(crate) expr: ScheduleExpr,
    pub(crate) timezone: Option<String>,
    pub(crate) except: Vec<Exception>,
    pub(crate) until: Option<UntilSpec>,
    pub(crate) anchor: Option<jiff::civil::Date>,
    pub(crate) during: Vec<MonthName>,
}

impl Schedule {
    /// Create a Schedule from just an expression (no modifiers).
    pub fn new(expr: ScheduleExpr) -> Self {
        Self {
            expr,
            timezone: None,
            except: Vec::new(),
            until: None,
            anchor: None,
            during: Vec::new(),
        }
    }
}

/// The core schedule expression (what repeats).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScheduleExpr {
    /// `every 30 min from 09:00 to 17:00 [on weekdays]`
    IntervalRepeat {
        interval: u32,
        unit: IntervalUnit,
        from: TimeOfDay,
        to: TimeOfDay,
        day_filter: Option<DayFilter>,
    },
    /// `every day at 09:00`, `every 2 days at 09:00`
    DayRepeat {
        interval: u32,
        days: DayFilter,
        times: Vec<TimeOfDay>,
    },
    /// `every 2 weeks on monday at 09:00`
    WeekRepeat {
        interval: u32,
        days: Vec<Weekday>,
        times: Vec<TimeOfDay>,
    },
    /// `every month on the 1st at 09:00`, `every 2 months on the 1st at 09:00`
    MonthRepeat {
        interval: u32,
        target: MonthTarget,
        times: Vec<TimeOfDay>,
    },
    /// `on feb 14 at 9:00, 17:00`
    SingleDate {
        date: DateSpec,
        times: Vec<TimeOfDay>,
    },
    /// `every year on dec 25 at 00:00`, `every 2 years on dec 25 at 00:00`
    YearRepeat {
        interval: u32,
        target: YearTarget,
        times: Vec<TimeOfDay>,
    },
}

/// Exception date for `except` clause.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Exception {
    /// Recurring named date: `dec 25` matches every year.
    Named { month: MonthName, day: u8 },
    /// One-off ISO date: `2026-12-25`.
    Iso(String),
}

/// Until spec for `until` clause.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum UntilSpec {
    /// ISO date: `2026-12-31`.
    Iso(String),
    /// Named date: `dec 31` — resolves to next occurrence from current year.
    Named { month: MonthName, day: u8 },
}

/// Year target for yearly expressions.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum YearTarget {
    /// `on dec 25` — specific month and day.
    Date { month: MonthName, day: u8 },
    /// `on the first monday of march` — ordinal weekday of a month.
    OrdinalWeekday {
        ordinal: OrdinalPosition,
        weekday: Weekday,
        month: MonthName,
    },
    /// `on the 15th of march` — day of a month.
    DayOfMonth { day: u8, month: MonthName },
    /// `on the last weekday of december` — last weekday of a month.
    LastWeekday { month: MonthName },
}

/// Time of day (hours and minutes).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct TimeOfDay {
    pub hour: u8,
    pub minute: u8,
}

#[cfg(feature = "serde")]
impl Serialize for TimeOfDay {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&format!("{:02}:{:02}", self.hour, self.minute))
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for TimeOfDay {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() != 2 {
            return Err(serde::de::Error::custom("expected HH:MM"));
        }
        let hour: u8 = parts[0]
            .parse()
            .map_err(|_| serde::de::Error::custom("invalid hour"))?;
        let minute: u8 = parts[1]
            .parse()
            .map_err(|_| serde::de::Error::custom("invalid minute"))?;
        if hour > 23 {
            return Err(serde::de::Error::custom("hour must be 0-23"));
        }
        if minute > 59 {
            return Err(serde::de::Error::custom("minute must be 0-59"));
        }
        Ok(TimeOfDay { hour, minute })
    }
}

/// Day filter for day-repeat and interval expressions.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum DayFilter {
    Every,
    Weekday,
    Weekend,
    Days(Vec<Weekday>),
}

/// Weekday with custom serde (lowercase string).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

impl Weekday {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Monday => "monday",
            Self::Tuesday => "tuesday",
            Self::Wednesday => "wednesday",
            Self::Thursday => "thursday",
            Self::Friday => "friday",
            Self::Saturday => "saturday",
            Self::Sunday => "sunday",
        }
    }

    pub fn short(self) -> &'static str {
        match self {
            Self::Monday => "mon",
            Self::Tuesday => "tue",
            Self::Wednesday => "wed",
            Self::Thursday => "thu",
            Self::Friday => "fri",
            Self::Saturday => "sat",
            Self::Sunday => "sun",
        }
    }

    pub(crate) fn to_jiff(self) -> jiff::civil::Weekday {
        match self {
            Self::Monday => jiff::civil::Weekday::Monday,
            Self::Tuesday => jiff::civil::Weekday::Tuesday,
            Self::Wednesday => jiff::civil::Weekday::Wednesday,
            Self::Thursday => jiff::civil::Weekday::Thursday,
            Self::Friday => jiff::civil::Weekday::Friday,
            Self::Saturday => jiff::civil::Weekday::Saturday,
            Self::Sunday => jiff::civil::Weekday::Sunday,
        }
    }

    pub(crate) fn from_jiff(wd: jiff::civil::Weekday) -> Self {
        match wd {
            jiff::civil::Weekday::Monday => Self::Monday,
            jiff::civil::Weekday::Tuesday => Self::Tuesday,
            jiff::civil::Weekday::Wednesday => Self::Wednesday,
            jiff::civil::Weekday::Thursday => Self::Thursday,
            jiff::civil::Weekday::Friday => Self::Friday,
            jiff::civil::Weekday::Saturday => Self::Saturday,
            jiff::civil::Weekday::Sunday => Self::Sunday,
        }
    }

    /// ISO 8601 day number: Monday=1, Sunday=7.
    pub fn number(self) -> u8 {
        match self {
            Self::Monday => 1,
            Self::Tuesday => 2,
            Self::Wednesday => 3,
            Self::Thursday => 4,
            Self::Friday => 5,
            Self::Saturday => 6,
            Self::Sunday => 7,
        }
    }

    pub fn from_number(n: u8) -> Option<Self> {
        match n {
            1 => Some(Self::Monday),
            2 => Some(Self::Tuesday),
            3 => Some(Self::Wednesday),
            4 => Some(Self::Thursday),
            5 => Some(Self::Friday),
            6 => Some(Self::Saturday),
            7 => Some(Self::Sunday),
            _ => None,
        }
    }

    pub fn all_weekdays() -> Vec<Self> {
        vec![
            Self::Monday,
            Self::Tuesday,
            Self::Wednesday,
            Self::Thursday,
            Self::Friday,
        ]
    }

    pub fn all_weekend() -> Vec<Self> {
        vec![Self::Saturday, Self::Sunday]
    }
}

#[cfg(feature = "serde")]
impl Serialize for Weekday {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Weekday {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        parse_weekday(&s).ok_or_else(|| serde::de::Error::custom(format!("unknown weekday: {s}")))
    }
}

pub(crate) fn parse_weekday(s: &str) -> Option<Weekday> {
    match s.to_lowercase().as_str() {
        "monday" | "mon" => Some(Weekday::Monday),
        "tuesday" | "tue" => Some(Weekday::Tuesday),
        "wednesday" | "wed" => Some(Weekday::Wednesday),
        "thursday" | "thu" => Some(Weekday::Thursday),
        "friday" | "fri" => Some(Weekday::Friday),
        "saturday" | "sat" => Some(Weekday::Saturday),
        "sunday" | "sun" => Some(Weekday::Sunday),
        _ => None,
    }
}

/// A single day or range of days in a monthly target.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum DayOfMonthSpec {
    Single(u8),
    Range(u8, u8),
}

impl DayOfMonthSpec {
    /// Expand into individual day numbers.
    pub fn expand(&self) -> Vec<u8> {
        match self {
            DayOfMonthSpec::Single(d) => vec![*d],
            DayOfMonthSpec::Range(start, end) => (*start..=*end).collect(),
        }
    }
}

/// Direction for nearest weekday (hron extension beyond cron W).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum NearestDirection {
    /// Always prefer following weekday (can cross to next month).
    Next,
    /// Always prefer preceding weekday (can cross to prev month).
    Previous,
}

/// Month target for month-repeat expressions.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum MonthTarget {
    Days(Vec<DayOfMonthSpec>),
    LastDay,
    LastWeekday,
    /// Nearest weekday to a given day of month.
    /// Standard (None): never crosses month boundary (cron W compatibility).
    /// Directional (Some): can cross month boundary.
    NearestWeekday {
        day: u8,
        direction: Option<NearestDirection>,
    },
    /// Ordinal weekday of month: `first monday`, `last friday`, etc.
    OrdinalWeekday {
        ordinal: OrdinalPosition,
        weekday: Weekday,
    },
}

impl MonthTarget {
    /// Expand all day specs into individual day numbers.
    pub(crate) fn expand_days(&self) -> Vec<u8> {
        match self {
            MonthTarget::Days(specs) => specs.iter().flat_map(|s| s.expand()).collect(),
            _ => vec![],
        }
    }
}

/// Ordinal position (first through fifth, or last).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum OrdinalPosition {
    First,
    Second,
    Third,
    Fourth,
    Fifth,
    Last,
}

impl OrdinalPosition {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::First => "first",
            Self::Second => "second",
            Self::Third => "third",
            Self::Fourth => "fourth",
            Self::Fifth => "fifth",
            Self::Last => "last",
        }
    }
}

/// Date specification for single-date expressions.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum DateSpec {
    Named { month: MonthName, day: u8 },
    Iso(String),
}

/// Month name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum MonthName {
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December,
}

impl MonthName {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::January => "jan",
            Self::February => "feb",
            Self::March => "mar",
            Self::April => "apr",
            Self::May => "may",
            Self::June => "jun",
            Self::July => "jul",
            Self::August => "aug",
            Self::September => "sep",
            Self::October => "oct",
            Self::November => "nov",
            Self::December => "dec",
        }
    }

    pub fn number(self) -> u8 {
        match self {
            Self::January => 1,
            Self::February => 2,
            Self::March => 3,
            Self::April => 4,
            Self::May => 5,
            Self::June => 6,
            Self::July => 7,
            Self::August => 8,
            Self::September => 9,
            Self::October => 10,
            Self::November => 11,
            Self::December => 12,
        }
    }
}

pub(crate) fn parse_month_name(s: &str) -> Option<MonthName> {
    match s.to_lowercase().as_str() {
        "january" | "jan" => Some(MonthName::January),
        "february" | "feb" => Some(MonthName::February),
        "march" | "mar" => Some(MonthName::March),
        "april" | "apr" => Some(MonthName::April),
        "may" => Some(MonthName::May),
        "june" | "jun" => Some(MonthName::June),
        "july" | "jul" => Some(MonthName::July),
        "august" | "aug" => Some(MonthName::August),
        "september" | "sep" => Some(MonthName::September),
        "october" | "oct" => Some(MonthName::October),
        "november" | "nov" => Some(MonthName::November),
        "december" | "dec" => Some(MonthName::December),
        _ => None,
    }
}

/// Interval unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum IntervalUnit {
    Minutes,
    Hours,
}

impl IntervalUnit {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Minutes => "min",
            Self::Hours => "hours",
        }
    }
}