Grav v1.14.0

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 * * * *"))
}
Output
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 takes L (the last day) and LW (the last weekday); day of week takes 5L (the last Friday) and 1#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 after from; previous(from) strictly before; nextTimes(from, n) gives several. An expression that can never match (0 0 30 2 *) is a StateError there; a malformed one is a ValueError from parse (isValid says 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: string
  • hasSeconds: bool = false

Methods

  • fn isDue(t: DateTime, utc: bool = false) -> bool — Whether it is due at t (to the minute; to the second with a seconds field).
  • fn isDueUnix(unix: long, utc: bool = false) -> bool
  • fn next(from: DateTime, utc: bool = false) -> DateTime — The first time after from when it is due (StateError if never).
  • fn previous(from: DateTime, utc: bool = false) -> DateTime — The last time before from when it was due.
  • fn nextUnix(from: long, utc: bool = false) -> long
  • fn nextTimes(from: DateTime, n: int, utc: bool = false) -> Array<DateTime> — The next n times after from.
  • fn toString() -> string

Edit this page on GitHub