croncheck — validate a cron expression, in a window

croncheck — validate a cron expression, in a window

croncheck is a LightGUI (Python/XFrame) port of the croncheck utility from util_box: validate a cron expression and show the next run times, with the weekday of each run. It is one of the 50 apps in util_boxgui, the project recreating util_box utilities as LightGUI apps. The full source is apps/python/croncheck/croncheck.py in that repo.

The app opens with 0 9 * * 1-5 already typed and today already filled in as the start date, so the next five weekday-9am runs are already shown — the screenshot below is the default state, not a staged one. Type in any entry and it re-validates live; the Validate button validates too.

The GUI layout

croncheck running under Xvfb
croncheck running — 0 9 * * 1-5 from today, captured under Xvfb.

The window is 640×480 and holds nine widgets, created with create() + set_prop() and drawn on a single Gtk.DrawingArea:

  • Expression: a GtkLabel and a GtkEntry holding the cron expression to validate, e.g. 0 9 * * 1-5 or @daily. Pre-filled with 0 9 * * 1-5. Click the entry to focus it (a blue outline appears), then type — BackSpace deletes, Return validates.
  • From: a GtkLabel and a GtkEntry holding the start time, YYYY-MM-DD (or YYYY-MM-DD HH:MM). Pre-filled with today.
  • Validate button: a GtkButton that validates the expression now and drops entry focus.
  • Count: a GtkLabel and a GtkEntry holding how many next runs to show, pre-filled with 5, plus a hint label giving the field order: minute, hour, day-of-month, month, day-of-week.
  • Output area: a GtkTextView filling the rest of the window, showing VALID (or INVALID with the reason) plus one next: line per run, with the weekday, in a 13-point monospace font, with scroll bars. It is read-only — clicking it just drops the entry's focus.

Two honest limitations, both inherited from how LightGUI draws its widgets with Cairo on one drawing area: there is no native GTK keyboard focus, so this app wires focus and typing itself (click to focus, type to edit); and the output area does not really scroll — the text-view scroll bars are drawn, not functional. The report is short (at most count + 1 lines), so nothing is clipped in practice. A third limitation is the app's own: the CLI's --file mode (validate every expression in a crontab file) has no GUI equivalent — the GUI validates one expression at a time.

The source, in sections

croncheck.py is about 450 lines. It is modelled on the LightGUI Python examples gtkentry.py, gtkbutton.py and gtktextview.py: widgets are created with create() + set_prop(), drawn on a Gtk.DrawingArea by widget.draw(cr), hit-tested on click, and dispatched through a _HANDLERS table. The cron half, though, is not modelled on anything — it is vendored verbatim from the CLI, so the GUI can never drift from it.

The parsing. parse_expr() and expand_field() are copied byte-for-byte from the CLI script. Lists (1,15), ranges (1-5), steps (*/15), month and day names (jan, mon) and the @daily / @weekly / @hourly / @reboot shortcuts all work, and Sunday is both 0 and 7, exactly as in cron:

def expand_field(field, lo, hi, names=None):
    vals = set()
    for part in field.split(","):
        step = 1
        if "/" in part:
            part, step = part.split("/", 1)
            if not step.isdigit() or int(step) < 1:
                raise ValueError("bad step %r" % step)
            step = int(step)
        if part == "*":
            start, end = lo, hi
        elif "-" in part:
            s, e = part.split("-", 1)
            start, end = parse_num(s, names), parse_num(e, names)
        else:
            start = end = parse_num(part, names)
        if start < lo or end > hi or start > end:
            raise ValueError("value %r out of range %d-%d" % (part, lo, hi))
        vals.update(range(start, end + 1, step))
    return vals

def parse_expr(expr):
    expr = expr.strip()
    if expr in SHORTCUTS:
        if SHORTCUTS[expr] is None:
            return None  # @reboot has no schedule
        expr = SHORTCUTS[expr]
    fields = expr.split()
    if len(fields) != 5:
        raise ValueError("expected 5 fields, got %d" % len(fields))
    sets = []
    for i, f in enumerate(fields):
        if not re.match(r"^[A-Za-z0-9\*,\-/]+$", f):
            raise ValueError("bad characters in field %d: %r" % (i + 1, f))
        names = NAMES_M if i == 3 else (NAMES_D if i == 4 else None)
        sets.append(expand_field(f, RANGES[i][0], RANGES[i][1], names))
    # cron: Sunday is both 0 and 7
    if 7 in sets[4]:
        sets[4].add(0)
    return sets

The next runs. next_runs() is vendored verbatim too, including the cron day rule that trips up most reimplementations: if either day-of-month or day-of-week is *, the other decides; otherwise a run happens when either matches:

def next_runs(sets, start, n):
    out = []
    t = start.replace(second=0, microsecond=0) + datetime.timedelta(minutes=1)
    limit = start + datetime.timedelta(days=366)
    dom_star = len(sets[2]) == 31
    dow_star = len(sets[4]) == 8  # 0..7 after adding 0
    while len(out) < n and t <= limit:
        dom_ok = t.day in sets[2]
        dow_ok = (t.weekday() + 1) % 7 in sets[4]
        # cron rule: if either dom or dow is *, the other decides; else OR
        if dom_star and dow_star:
            day_ok = True
        elif dom_star:
            day_ok = dow_ok
        elif dow_star:
            day_ok = dom_ok
        else:
            day_ok = dom_ok or dow_ok
        if (t.minute in sets[0] and t.hour in sets[1] and t.month in sets[3] and day_ok):
            out.append(t)
        t += datetime.timedelta(minutes=1)
    return out

The report. validate_text() wraps the vendored code into the GUI's report — the VALID / INVALID lines and the next: YYYY-MM-DD HH:MM (Weekday) lines are the CLI's lines, so the GUI can be diffed against the CLI. @reboot is valid but has no scheduled times, and fewer runs than requested within a year prints (no further runs within a year):

def validate_text(expr_s, from_s, count_s):
    start = datetime.datetime.now()
    if from_s.strip():
        for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d"):
            try:
                start = datetime.datetime.strptime(from_s.strip(), fmt)
                break
            except ValueError:
                continue
        else:
            return "croncheck: bad --from date %r" % from_s
    try:
        count = int(count_s) if count_s.strip() else 5
    except ValueError:
        return "croncheck: bad -n value: %r (need an integer)" % count_s
    if not expr_s.strip():
        return "croncheck: an expression is required"
    try:
        sets = parse_expr(expr_s)
    except ValueError as e:
        return "INVALID  %-20s %s" % (expr_s, e)
    if sets is None:
        return ("VALID    %-20s (runs at system startup; no scheduled times)"
                % expr_s)
    runs = next_runs(sets, start, count)
    lines = ["VALID    %s" % expr_s]
    for t in runs:
        lines.append("  next: %s (%s)"
                     % (t.strftime("%Y-%m-%d %H:%M"), t.strftime("%A")))
    if len(runs) < count:
        lines.append("  (no further runs within a year)")
    return "\n".join(lines)

Events. Typing in any entry re-validates live — the key-press handler calls _validate() after every keystroke — and the Validate button calls the same function. main() is the standard LightGUI Python harness: a Gtk.Window titled croncheck - util_boxgui holding a Gtk.DrawingArea, with the draw, button-press, button-release and resize signals connected, and Gtk.main() running the loop.

Building and running it

There is nothing to build — it is pure Python. Run it with the LightGUI Python package on PYTHONPATH, under a real X server or under Xvfb (display :100 is the one used for this app). It needs python3-gi / gir1.2-gtk-3.0 and the LightGUI Python checkout:

cd apps/python/croncheck

PYTHONPATH=/root/lg-review/lightgui_python python3 croncheck.py

# Under Xvfb:
Xvfb :100 -screen 0 1024x768x24 &
DISPLAY=:100 PYTHONPATH=/root/lg-review/lightgui_python python3 croncheck.py

The PYTHONPATH above points at the LightGUI Python checkout on the build machine — on your own machine, point it at wherever you cloned LightGUI Python. The window title is croncheck - util_boxgui. Try 99 * * * * and watch it go INVALID with the reason, or @daily and watch the next five midnights appear.

What the CLI version does differently

Same parsing, same next-run logic, same report lines, same edge cases — and the differences are all about the medium. The CLI is croncheck "0 9 * * 1-5" [--from DATE] [-n N] [--file FILE] and prints to stdout; the GUI shows the report in the output area and never writes to stdout. The CLI's --file mode has no GUI equivalent. And the interaction model is the GUI's own: the CLI validates once and exits, the GUI re-validates on every keystroke — type 0 9 * * 1-5 one character at a time and watch it go from INVALID (too few fields) to VALID as the fifth field lands. The report was verified against the CLI for 0 9 * * 1-5 from 2026-12-07 (identical output), and for the invalid (99 * * * *), @daily, and @reboot cases.

See also

Source code: git.lightgui.com/thinkmelt/lightgui_python