Cron
import "std/sys" (included in import "std") · namespace std.sys
Cron expressions: whether one is due at a time, and when it is next (or was last) due, reading the fields in local time or, with utc true, in UTC.
grav
import "std"
fn main() {
let c = Cron.parse("*/15 9-17 * * MON-FRI") // every quarter hour in working hours
let friday = DateTime.ofUtc(2024, 3, 15, 17, 50)
print(c.next(friday, true).isoUtc()) // Monday morning
print(c.isDue(DateTime.ofUtc(2024, 3, 18, 9, 30), true))
for (t in Cron.parse("0 9 * * 1#2").nextTimes(friday, 2, true)) { print(t.isoUtc()) } // second Mondays
print(Cron.parse("0 0 L * *").next(DateTime.ofUtc(2024, 2, 3, 0, 0), true).isoUtc()) // the last day
print(Cron.isValid("61 * * * *"))
}2024-03-18T09:00:00Z
true
2024-04-08T09:00:00Z
2024-05-13T09:00:00Z
2024-02-29T00:00:00Z
false- Fields. Five (minute, hour, day of month, month, day of week), or six with seconds first. Each takes
*,?, numbers, names (JAN…DEC,SUN…SAT), lists (1,15), ranges (9-17) and steps (*/5,10-40/10). Day of month also takesL(the last day) andLW(the last weekday); day of week takes5L(the last Friday) and1#2(the second Monday), and 0 or 7 for Sunday. Shorthands:@yearly,@annually,@monthly,@weekly,@daily,@midnight,@hourly. - Both day fields restricted (
0 0 1,15 * MON): either one matching is enough, as in Vixie cron. next(from)is strictly afterfrom;previous(from)strictly before;nextTimes(from, n)gives several. An expression that can never match (0 0 30 2 *) is aStateErrorthere; a malformed one is aValueErrorfromparse(isValidsays which).- Speed. The search runs in C, skipping whole months, days and hours that cannot match: about 1.5 µs per
next, however rare the times are. Checked against a brute-force search on 400 random expressions.
API
class Cron
Constructors
new Cron(expression: string)
Static members
static fn parse(expression: string) -> Cron— The expression, or a ValueError saying what is wrong with it.static fn isValid(expression: string) -> bool
Fields
expression: stringhasSeconds: bool = false
Methods
fn isDue(t: DateTime, utc: bool = false) -> bool— Whether it is due att(to the minute; to the second with a seconds field).fn isDueUnix(unix: long, utc: bool = false) -> boolfn next(from: DateTime, utc: bool = false) -> DateTime— The first time afterfromwhen it is due (StateError if never).fn previous(from: DateTime, utc: bool = false) -> DateTime— The last time beforefromwhen it was due.fn nextUnix(from: long, utc: bool = false) -> longfn nextTimes(from: DateTime, n: int, utc: bool = false) -> Array<DateTime>— The nextntimes afterfrom.fn toString() -> string