Sign in

Scheduling

Job scheduling

A single-process scheduler that runs functions on a fixed interval, on a cron expression, or when a named event is triggered.

Overview

Much of ML operations is routine work on a clock: retrain every night, refresh features every few minutes, score when new data lands. A scheduler keeps a list of jobs with the time each should run next. Again and again it looks at the clock, runs whatever is due, and moves each job's next time forward. The hard part is what to do when the scheduler was busy or switched off and several runs were missed. Running all of them and running only the latest are both sensible, so it is a setting.

A short history

Time-based job scheduling goes back to the batch queues of mainframes. The cron utility appeared in Unix at Bell Labs in the 1970s and gave the five field expression of minute, hour, day of month, month and day of week. Paul Vixie's 1987 version became the one most Unix-like systems ship. Triggering work on events comes from messaging and event-driven design. Workflow tools for data teams combine both ideas.

How it works

  1. Register jobs: every(name, seconds, fn) for a fixed interval, cron(name, expression, fn) for calendar times in UTC, and on(name, event, fn) for events.
  2. Each timed job stores its next run time. For cron jobs, CronExpr.next_after finds the next minute that matches all five fields.
  3. run_pending() reads the clock and collects every job whose next run time has passed, earliest first.
  4. For each such job it lists all the occurrences that are now due and advances the job to its next future time.
  5. Occurrences later than misfire_grace_s are recorded as missed. With coalesce on, the rest collapse into a single run.
  6. trigger(event, payload) runs every job registered for that event at once. A job that raises is recorded in history and the scheduler carries on.

Watch out for

  • With coalesce off, a scheduler that was down for a day runs every missed occurrence in a burst when it comes back, which can overload whatever the job calls.
  • With coalesce on, a job that processes one hour of data per run silently loses the hours that were merged away. Such jobs need one run per occurrence.
  • Cron times here are in UTC, so 2 o'clock in an expression is not 2 o'clock local time, and it does not move with daylight saving.
  • A job that takes longer than its interval falls behind, and runs are then merged or pile up depending on the settings.
  • Jobs live in memory in one process. After a restart nothing remembers them, and two copies of the service would both run every job.

Use cases

When to use it

To retrain nightly, refresh features every few minutes, or start an evaluation when new data arrives, inside a single service. Jobs that must survive restarts or run on several machines need a full scheduler.

In industry

Retail forecasting
A demand model is retrained every night after the day's sales are loaded, using a cron expression set to a quiet hour.
Online platforms
Feature tables such as recent click counts are refreshed every few minutes on a fixed interval, so the serving model reads fresh values.
Data operations
An evaluation job is triggered by the event that a new labelled batch has arrived, not by the clock, so it never runs on stale data.

Choosing it: what must hold

  • Work that repeats on a timetable or in response to a named event.
  • A process that stays running to hold the schedule.
  • Jobs that tolerate a missed or late run when that process is down.
  • A policy for runs that overlap or were missed, such as skip or catch up.

When to choose something else

IfUse instead
Jobs must survive restarts or run across several machinesA full scheduler such as system cron, Apache Airflow or Kubernetes CronJobs
The job is a chain of dependent stepsThe pipeline runner lesson, started by this scheduler
The work runs once, by handCall the function directly, no scheduler needed

Math foundations

  1. Occurrences of an interval job

    tk=t0+k Δ,k=0,1,2,…t_k = t_0 + k\,\Delta, \qquad k = 0, 1, 2, \dots

    An interval job is due at evenly spaced times. The first, t0t_0, is one interval after registration unless start_at is given.

  2. How many occurrences are due

    m=⌊tnow−tnextΔ⌋+1when tnow≥tnextm = \left\lfloor \frac{t_{\text{now}} - t_{\text{next}}}{\Delta} \right\rfloor + 1 \qquad \text{when } t_{\text{now}} \ge t_{\text{next}}

    When the scheduler looks at the clock, this many occurrences of the job have come due since it last ran. Normally m=1m = 1. A larger value means runs were missed.

  3. The misfire rule

    occurrence at t is run  ⟺  tnow−t≤g\text{occurrence at } t \text{ is run} \iff t_{\text{now}} - t \le g

    An occurrence that is more than gg seconds late is recorded as missed and not run. With g=0g = 0 the rule is off and nothing is dropped for lateness.

  4. When a cron expression fires

    fires at t  ⟺  minute⁡(t)∈M  ∧  hour⁡(t)∈H  ∧  month⁡(t)∈N  ∧  day⁡(t) matches\text{fires at } t \iff \operatorname{minute}(t) \in M \;\wedge\; \operatorname{hour}(t) \in H \;\wedge\; \operatorname{month}(t) \in N \;\wedge\; \operatorname{day}(t) \text{ matches}

    Each field of the expression is a set of allowed values and a time fires when it is in all of them. For the day, if both day-of-month and day-of-week are restricted, matching either is enough, as in standard cron.

Symbols

t0t_0
time of the first occurrence
Δ\Delta
interval between occurrences in seconds
tkt_k
time of occurrence number k
tnowt_{\text{now}}
current clock time
tnextt_{\text{next}}
the job's stored next run time
mm
number of occurrences that are due
gg
misfire_grace_s
M, H, NM,\, H,\, N
allowed minutes, hours and months of a cron expression

Worked by hand

A job is registered at 10:07 to run every 60 seconds, so its first run is due at 10:08. The clock then jumps to 10:15 before run_pending is called.

m=⌊10:15−10:0860 s⌋+1=⌊420 s60 s⌋+1=8m = \left\lfloor \frac{10{:}15 - 10{:}08}{60\ \text{s}} \right\rfloor + 1 = \left\lfloor \frac{420\ \text{s}}{60\ \text{s}} \right\rfloor + 1 = 8
coalesce on:8 occurrences→1 run, for 10:15\text{coalesce on:} \quad 8 \text{ occurrences} \to 1 \text{ run, for } 10{:}15
g=120 s:tnow−t≤120 s  ⟺  t≥10:13⇒5 missed,  3 keptg = 120\ \text{s}: \quad t_{\text{now}} - t \le 120\ \text{s} \iff t \ge 10{:}13 \quad \Rightarrow \quad 5 \text{ missed},\; 3 \text{ kept}
tnext=10:16t_{\text{next}} = 10{:}16

Eight occurrences are due. By default they become one run. With a grace of 120 seconds and coalesce off, the five oldest are recorded as missed and three are run.

Visual example

Loading the example.

Try this

  • Leave the clock at 10:15 and read how eight due occurrences become one run.
  • Turn coalesce off and set the grace to 120 seconds: five are recorded as missed and three run.
  • Type a cron expression such as 0 9 * * 1 and read the next three times it fires.

Code sample

from datetime import datetime, timezone
from impl import Scheduler, CronExpr
from config import SchedulingConfig

now = [datetime(2024, 1, 1, 10, 7, tzinfo=timezone.utc).timestamp()]   # a clock we move by hand
scheduler = Scheduler(SchedulingConfig(), clock=lambda: now[0])
scheduler.every("refresh", 60, lambda: print("refresh features"))
scheduler.cron("retrain", "*/15 * * * *", lambda: print("retrain"))
scheduler.on("score", "new_data", lambda payload: print("score", payload))

now[0] += 8 * 60                      # 10:15
print(scheduler.run_pending())        # ['refresh', 'retrain']
print(scheduler.trigger("new_data", {"rows": 120}))                    # ['score']
print(CronExpr("0 9 * * 1").next_after(datetime(2024, 1, 1, 10, 7, tzinfo=timezone.utc)))   # Monday 2024-01-08 09:00
Read the implementation (226 lines)
"""Scheduled and triggered runs: interval jobs, cron jobs and event-triggered jobs in one process.

Standard library only. The scheduler never reads the wall clock directly: it asks a `clock` function for
the current time in seconds, so tests (and backfills) can drive it with a simulated clock, while
`start()` runs it against real time on a background thread. Cron times are evaluated in UTC.
"""
from __future__ import annotations

import threading
import time
from collections import deque
from datetime import datetime, timedelta, timezone
from typing import Callable

try:
    from .config import SchedulingConfig
except ImportError:  # run from the template's own folder
    from config import SchedulingConfig

# name, lowest and highest value of the five cron fields
_FIELDS = (("minute", 0, 59), ("hour", 0, 23), ("day of month", 1, 31), ("month", 1, 12), ("day of week", 0, 7))


def _parse_field(text: str, name: str, low: int, high: int) -> frozenset:
    """Expand one cron field ("*", "5", "1-5", "*/15", "0-30/10", "1,15") into the set of matching numbers."""
    values = set()
    for part in text.split(","):
        base, _, step_text = part.partition("/")
        try:
            step = int(step_text) if step_text else 1
            if base == "*":
                start, stop = low, high
            elif "-" in base:
                start, stop = (int(v) for v in base.split("-"))
            else:
                start = int(base)
                stop = high if step_text else start
        except ValueError:
            raise ValueError(f"cannot read cron {name} field {text!r}") from None
        if step < 1 or start < low or stop > high or start > stop:
            raise ValueError(f"cron {name} field {text!r} is outside {low}-{high}")
        values.update(range(start, stop + 1, step))
    return frozenset(values)


class CronExpr:
    """A five-field cron expression: minute hour day-of-month month day-of-week.

    Each field takes "*", a number, a range "a-b", a list "a,b,c" and a step "*/n" or "a-b/n".
    Day of week is 0-6 with 0 = Sunday (7 is also Sunday). Names such as MON or JAN are not supported.
    As in standard cron, when both day-of-month and day-of-week are restricted, a day matches if EITHER does.
    """

    def __init__(self, expression: str) -> None:
        parts = expression.split()
        if len(parts) != 5:
            raise ValueError(f"a cron expression has 5 fields, got {len(parts)} in {expression!r}")
        self.expression = expression
        sets = [_parse_field(part, *spec) for part, spec in zip(parts, _FIELDS)]
        self.minutes, self.hours, self.days, self.months = sets[:4]
        self.weekdays = frozenset(day % 7 for day in sets[4])       # fold 7 onto 0
        self._day_any = parts[2] == "*"
        self._weekday_any = parts[4] == "*"

    def _day_matches(self, moment: datetime) -> bool:
        in_month = moment.day in self.days
        in_week = (moment.weekday() + 1) % 7 in self.weekdays       # Python: Monday = 0, cron: Sunday = 0
        if self._day_any or self._weekday_any:
            return in_month and in_week
        return in_month or in_week

    def matches(self, moment: datetime) -> bool:
        """True when the expression fires in the minute of `moment`."""
        return (moment.month in self.months and self._day_matches(moment)
                and moment.hour in self.hours and moment.minute in self.minutes)

    def next_after(self, moment: datetime) -> datetime:
        """The first firing time strictly after `moment` (seconds are dropped)."""
        t = moment.replace(second=0, microsecond=0) + timedelta(minutes=1)
        limit = t + timedelta(days=366 * 8)                         # covers "29 2" (leap day) expressions
        while t < limit:
            if t.month not in self.months:                          # jump to the first minute of the next month
                t = (t.replace(day=1, hour=0, minute=0) + timedelta(days=32)).replace(day=1)
            elif not self._day_matches(t):
                t = t.replace(hour=0, minute=0) + timedelta(days=1)
            elif t.hour not in self.hours:
                t = t.replace(minute=0) + timedelta(hours=1)
            elif t.minute not in self.minutes:
                t += timedelta(minutes=1)
            else:
                return t
        raise ValueError(f"cron expression {self.expression!r} never fires")


class _Job:
    """One registered job. `advance(t)` returns the occurrence after the occurrence at time t."""

    def __init__(self, name: str, function: Callable, next_run: float | None, advance: Callable | None) -> None:
        self.name, self.function, self.next_run, self.advance = name, function, next_run, advance


class Scheduler:
    """Run functions on a time interval, on a cron schedule, or when an event is triggered.

    clock: function returning the current time in seconds (Unix time). Default: time.time.
    history: the most recent runs, each a dict with "job", "scheduled_for", "ran_at", "status"
             ("ok", "error" or "missed") and "error" (the exception text or None).
    """

    def __init__(self, config: SchedulingConfig | None = None, clock: Callable[[], float] = time.time) -> None:
        self.config = config or SchedulingConfig()
        self.clock = clock
        self.history: deque = deque(maxlen=self.config.max_history)
        self._jobs: dict[str, _Job] = {}
        self._listeners: dict[str, list[str]] = {}
        self._lock = threading.RLock()
        self._stop = threading.Event()
        self._thread: threading.Thread | None = None

    # ------------------------------------------------------------------------------------- registration
    def _add(self, job: _Job) -> None:
        with self._lock:
            if job.name in self._jobs:
                raise ValueError(f"job {job.name!r} is already scheduled")
            self._jobs[job.name] = job

    def every(self, name: str, seconds: float, function: Callable, start_at: float | None = None) -> None:
        """Run `function()` every `seconds`. First run at `start_at`, or one interval from now."""
        if seconds <= 0:
            raise ValueError(f"seconds must be positive, got {seconds}")
        first = self.clock() + seconds if start_at is None else start_at
        self._add(_Job(name, function, first, lambda t: t + seconds))

    def cron(self, name: str, expression: str, function: Callable) -> None:
        """Run `function()` at the UTC times a cron expression describes, for example "30 2 * * 1"."""
        expr = CronExpr(expression)

        def advance(t: float) -> float:
            return expr.next_after(datetime.fromtimestamp(t, tz=timezone.utc)).timestamp()

        self._add(_Job(name, function, advance(self.clock()), advance))

    def on(self, name: str, event: str, function: Callable) -> None:
        """Run `function(payload)` every time `trigger(event, payload)` is called."""
        self._add(_Job(name, function, None, None))
        self._listeners.setdefault(event, []).append(name)

    def remove(self, name: str) -> None:
        """Unschedule a job."""
        with self._lock:
            del self._jobs[name]
            for names in self._listeners.values():
                if name in names:
                    names.remove(name)

    def next_run(self, name: str) -> float | None:
        """Time of the next scheduled run of a job (None for an event-triggered job)."""
        return self._jobs[name].next_run

    # ------------------------------------------------------------------------------------------ running
    def _execute(self, job: _Job, scheduled_for: float | None, now: float, *args) -> bool:
        """Call the job, catch its error, and append a history record. Returns True when it succeeded."""
        record = {"job": job.name, "scheduled_for": scheduled_for, "ran_at": now, "status": "ok", "error": None}
        try:
            job.function(*args)
        except Exception as error:  # one failing job must not stop the scheduler
            record["status"], record["error"] = "error", repr(error)
        self.history.append(record)
        return record["status"] == "ok"

    def run_pending(self) -> list[str]:
        """Run every job that is due at the current clock time. Returns the names that ran, in order.

        Call it in a loop (that is what `start()` does) or by hand after moving a simulated clock.
        """
        cfg = self.config
        now = self.clock()
        ran: list[str] = []
        with self._lock:
            due = sorted((job for job in self._jobs.values() if job.next_run is not None and job.next_run <= now),
                         key=lambda job: job.next_run)
            for job in due:
                occurrences = []
                while job.next_run <= now:
                    occurrences.append(job.next_run)
                    job.next_run = job.advance(job.next_run)
                if cfg.misfire_grace_s:
                    for late in [t for t in occurrences if now - t > cfg.misfire_grace_s]:
                        self.history.append({"job": job.name, "scheduled_for": late, "ran_at": None,
                                             "status": "missed", "error": None})
                    occurrences = [t for t in occurrences if now - t <= cfg.misfire_grace_s]
                if cfg.coalesce:
                    occurrences = occurrences[-1:]          # one run stands in for all the missed ones
                for scheduled_for in occurrences:
                    self._execute(job, scheduled_for, now)
                    ran.append(job.name)
        return ran

    def trigger(self, event: str, payload=None) -> list[str]:
        """Fire an event: run every job registered for it with `on`, passing the payload. Returns their names."""
        with self._lock:
            names = list(self._listeners.get(event, []))
            for name in names:
                self._execute(self._jobs[name], None, self.clock(), payload)
        return names

    # ------------------------------------------------------------------------------------ real-time loop
    def start(self) -> None:
        """Start a background thread that calls `run_pending` every tick_seconds."""
        if self._thread is not None:
            raise RuntimeError("the scheduler is already running")
        self._stop.clear()

        def loop() -> None:
            while not self._stop.wait(self.config.tick_seconds):
                self.run_pending()

        self._thread = threading.Thread(target=loop, name="scheduler", daemon=True)
        self._thread.start()

    def stop(self) -> None:
        """Stop the background thread and wait for it."""
        if self._thread is not None:
            self._stop.set()
            self._thread.join()
            self._thread = None
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
12, run with python3 -m unittest -v

Practice

Create a Scheduler with a hand-moved clock as in the template's README and register every("refresh", 60, fn). Advance the clock by 8 minutes, call run_pending() and inspect history. Repeat with SchedulingConfig(coalesce=False) and then with misfire_grace_s=120, and count the ok and missed records each time.

Check on learning

  1. A job adds yesterday's sales to a running total. The scheduler is down for three days. Should coalesce be on or off, and what goes wrong with the other choice?
    A way to think about it

    Ask whether one run can do the work of three. Compare with a job that rebuilds a whole table from scratch each time.

  2. Why does the scheduler take its time from an injectable clock function instead of always reading the system clock?
    A way to think about it

    Think about how you would test a job that runs once a week, or rerun last month's schedule on purpose.

  3. A cron job is set for 02:30 every day and takes 40 minutes. What happens if it one day takes 25 hours?
    A way to think about it

    Work out which occurrences come due while it is still running, and what the two missed-run settings do with them.

  4. Two copies of your service are started for reliability, each with this scheduler. What happens to the nightly retraining job, and what would a fix need?
    A way to think about it

    Each process has its own job list and knows nothing of the other. Consider what shared thing both could check before running.

  5. When is an event trigger a better choice than a short interval for starting a scoring job?
    A way to think about it

    With an interval the job often runs with nothing to do, or waits up to one interval after the data arrived. Compare both costs with a trigger.