APScheduler cron jobs: schedule and monitor

On this page

APScheduler can drop a run without raising anything: a job still running when the next one is due counts as a misfire, a scheduler that was down misses runs, and with the default settings a late run can simply not happen. Job events give you the hooks to report each outcome.

How can a scheduled job fail silently on APScheduler?

  • By default only one instance of each job may run at a time. If the previous run has not finished, the new run is a misfire.
  • A job that could not run on time is checked against its misfire_grace_time. A run later than that is bypassed, so a scheduler restart can skip a whole day.
  • Without coalescing, several missed runs can fire one after another when the scheduler comes back. With coalescing they collapse into one run.
  • The default job store is memory, so jobs vanish when the process ends unless you configure a persistent store such as SQLAlchemy.
  • If the executor has no free threads, a delayed run may be skipped for being too late, and the docs suggest more workers or a longer misfire_grace_time.

What are the limits of APScheduler?

LimitWhat the documentation says
Concurrent instancesOne per job by default; max_instances changes it.
misfire_grace_timeSettable per job or globally; a run later than this is not triggered.
CoalescingRolls queued missed runs into a single run when enabled.
Job storesMemoryJobStore by default; SQLAlchemy, MongoDB and others persist jobs.
Time zoneThe scheduler has a time zone; the examples in the docs use UTC.

How do you add a CronMissed ping to APScheduler?

Add one listener for executed, error and missed events. Keep a map from job id to ping URL. The listener sends the plain URL on success, /fail on an error, and /fail on a miss so a skipped run is reported at once.

scheduler.py
import urllib.request
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, EVENT_JOB_MISSED
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

PINGS = {"nightly-cleanup": "https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10"}

def ping(job_id, suffix="", body=None):
    base = PINGS.get(job_id)
    if base is None:
        return
    request = urllib.request.Request(base + suffix, data=body, method="POST" if body else "GET")
    try:
        urllib.request.urlopen(request, timeout=10).read()
    except OSError:
        pass  # a lost ping must never break the scheduler

def on_event(event):
    if event.code == EVENT_JOB_EXECUTED:
        ping(event.job_id)
    elif event.code == EVENT_JOB_ERROR:
        ping(event.job_id, "/fail", str(event.exception).encode()[-100000:])
    elif event.code == EVENT_JOB_MISSED:
        ping(event.job_id, "/fail", b"misfire: the run was skipped")

scheduler = BackgroundScheduler(timezone="UTC", job_defaults={"coalesce": True, "misfire_grace_time": 300})
scheduler.add_listener(on_event, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR | EVENT_JOB_MISSED)
scheduler.add_job(cleanup, CronTrigger.from_crontab("15 3 * * *"), id="nightly-cleanup")
scheduler.start()

How do you schedule a cron job in APScheduler?

Give add_job a CronTrigger. CronTrigger.from_crontab reads a standard five-field crontab line, and the scheduler's timezone decides which clock the fields are read in.

scheduler.py, schedule a job
scheduler.add_job(cleanup, CronTrigger.from_crontab("15 3 * * *"), id="nightly-cleanup")

That runs cleanup at 03:15 every day. Check a line with the cron expression translator before you add it, and see Python cron jobs for running a script from the system cron instead.

Which check settings fit APScheduler?

Create a cron check with the same crontab and the scheduler's time zone. The misfire_grace_time you pick should be shorter than the check's grace, so that a run APScheduler would still start is not already reported. Because the listener cannot report a process that has died, the heartbeat is also what catches a stopped scheduler.

How do you confirm the check works?

  1. Schedule the job every minute for a test, and confirm the ping arrives after each run.
  2. Make the job sleep longer than its interval to produce a misfire, and confirm the /fail ping.
  3. Stop the process and confirm the check goes late, then down.

Sources

Questions and answers

Is the success ping sent before or after the job ends?
After. EVENT_JOB_EXECUTED fires once the job function has returned without an error, so the ping means the work finished.
Does this work with the 4.x releases of APScheduler?
The listener API differs between 3.x and the newer major version. These examples follow the 3.x user guide; check your version's event classes before copying.
Know when this job stops

Create a check, add the ping to the job, and CronMissed alerts you the first time a run is late or reports a failure.

Start monitoring