← Blog
A lavender desk calendar with blank ivory cards, dark purple rings, and an orange tab.
Published on
2026-11-19

APScheduler in Python: persistent jobs and missed runs

APScheduler schedules Python functions for a later time or a recurring interval. It is useful when the application needs to create and manage those schedules. A persistent job store can retain the schedule across process restarts, but you still need to decide how late a run may start, whether missed runs should be combined, and what happens if the previous run is still working.

This guide builds a small APScheduler 3.x example with SQLite. It saves an importable job, stops the scheduler process, starts another process, and checks the result. The job refreshes a synthetic report, so the example can demonstrate repeated execution without contacting an external service.

Choose application scheduling for an application-owned schedule

Use APScheduler when Python code needs to add, inspect, or change schedules as part of application behavior. If the task is simply to launch a script on a host’s timetable, start with systemd timers versus cron. If an existing crontab entry has stopped working, the cron troubleshooting guide addresses that problem directly.

The example pins APScheduler 3.11.3, SQLAlchemy 2.1.9, and tzdata 2026.6. We checked the APScheduler package release and used the matching 3.x documentation. Keep that API generation consistent when adapting the code; examples from another major version may use different scheduling and coordination behavior.

Create an isolated Python environment, then install the tested package versions:

python -m pip install APScheduler==3.11.3 SQLAlchemy==2.1.9 tzdata==2026.6

The recorded tests ran on Python 3.12.14 under Windows. SQLite keeps this demonstration local and inspectable; it does not establish a production database choice or a distributed scheduler design.

Make the job importable and its result repeatable

Save this as jobs.py. The callable lives at module level so a later Python process can import it. Its only argument is a database path. It writes a report for one fixed synthetic batch and records successful attempts in a separate table.

import os
import sqlite3
from contextlib import closing
from datetime import datetime, timezone


def refresh_report(database):
    """Refresh one synthetic report; repeated calls keep the same report row."""
    total = sum([12, 18, 25])
    with closing(sqlite3.connect(database)) as connection, connection:
        connection.execute(
            "CREATE TABLE IF NOT EXISTS reports "
            "(batch TEXT PRIMARY KEY, total INTEGER NOT NULL)"
        )
        connection.execute(
            "CREATE TABLE IF NOT EXISTS attempts "
            "(finished_at TEXT NOT NULL, pid INTEGER NOT NULL)"
        )
        connection.execute(
            "INSERT INTO reports VALUES (?, ?) ON CONFLICT(batch) "
            "DO UPDATE SET total=excluded.total", ("demo-batch", total)
        )
        connection.execute("INSERT INTO attempts VALUES (?, ?)",
                           (datetime.now(timezone.utc).isoformat(), os.getpid()))
    return total

The three sample values sum to 55. Repeating the job updates the same report row rather than appending another business result. The attempts table deliberately grows, allowing us to see which process completed each call. Both writes belong to the same SQLite transaction, and the connection closes afterward.

This is idempotency for one narrow database effect. It says nothing about repeated payments, email, or external API calls. Those operations need their own identifiers and deduplication rules. A scheduler cannot make an arbitrary job safe to repeat.

Persist the job without resetting it at every startup

Save the following as scheduler_service.py beside the job module. The scheduler starts paused so it can inspect the stored job before processing due work. Normal startup creates the job only when its stable ID is absent. The explicit replace mode changes the stored schedule and recalculates its next run time.

import argparse
import json
import math
import os
from pathlib import Path
import time
from datetime import timezone
from apscheduler.events import (
    EVENT_JOB_EXECUTED, EVENT_JOB_ERROR, EVENT_JOB_MISSED, EVENT_JOB_MAX_INSTANCES,
)
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.background import BackgroundScheduler
from sqlalchemy.engine import URL
from sqlalchemy.pool import NullPool

JOB_ID = "refresh-demo-report"
EVENT_NAMES = {EVENT_JOB_EXECUTED: "executed", EVENT_JOB_ERROR: "error",
               EVENT_JOB_MISSED: "missed", EVENT_JOB_MAX_INSTANCES: "overlap_skipped"}


def make_scheduler(root):
    root = Path(root).resolve()
    root.mkdir(parents=True, exist_ok=True)
    store = SQLAlchemyJobStore(
        url=URL.create("sqlite", database=str(root / "jobs.sqlite")),
        engine_options={"poolclass": NullPool},
    )
    return BackgroundScheduler(
        jobstores={"default": store}, executors={"default": ThreadPoolExecutor(2)},
        timezone=timezone.utc,
        job_defaults={"coalesce": True, "max_instances": 1, "misfire_grace_time": 60},
    )


def ensure_report(scheduler, root, interval=2, replace=False):
    if scheduler.get_job(JOB_ID) is not None and not replace:
        return False
    scheduler.add_job(
        "jobs:refresh_report", "interval", seconds=interval, id=JOB_ID,
        args=[str(Path(root).resolve() / "reports.sqlite")], replace_existing=True,
    )
    return True


def run(root, mode="run", seconds=6, interval=2):
    events = []
    scheduler = make_scheduler(root)
    scheduler.add_listener(
        lambda event: events.append({"event": EVENT_NAMES[event.code], "job": event.job_id}),
        sum(EVENT_NAMES),
    )
    scheduler.start(paused=True)
    try:
        changed = ensure_report(scheduler, root, interval, replace=(mode == "replace"))
        job = scheduler.get_job(JOB_ID)
        print(json.dumps({"phase": "ready", "pid": os.getpid(), "changed": changed,
                          "job_count": len(scheduler.get_jobs()),
                          "next_run_time": job.next_run_time.isoformat()}), flush=True)
        if mode == "run":
            scheduler.resume()
            time.sleep(seconds)
    except KeyboardInterrupt:
        pass
    finally:
        scheduler.shutdown(wait=True)
    print(json.dumps({"phase": "stopped", "pid": os.getpid(), "events": events}), flush=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("mode", choices=["init", "run", "replace"])
    parser.add_argument("--root", default="scheduler-demo")
    parser.add_argument("--seconds", type=float, default=6)
    parser.add_argument("--interval", type=float, default=2)
    args = parser.parse_args()
    if not all(math.isfinite(x) and x > 0 for x in [args.seconds, args.interval]):
        parser.error("seconds and interval must be positive finite numbers")
    run(args.root, args.mode, args.seconds, args.interval)

The two SQLite files serve different purposes. jobs.sqlite holds scheduler state; reports.sqlite holds the job’s business result and attempt records. The SQLAlchemy job-store reference documents its serialized job storage. Keep that store trusted and access-controlled: it contains serialized Python job state, not an interchange format for untrusted uploads.

replace_existing=True ensures an intentional registration uses the same ID. It does not preserve the old next-run time when you supply a new schedule. That is why this example first checks for an existing job. In the tests, a second initialization preserved the exact timestamp; the deliberate replacement changed it while retaining one job.

The local store uses SQLAlchemy’s NullPool to close connections when returned rather than retain a pool. This made file cleanup predictable in the tested Windows fixture. It is an explicit choice for this small SQLite example, not a database performance recommendation.

Run a real stop-and-restart demonstration

Save this third file as demo.py and run python demo.py. It creates a temporary directory, invokes separate scheduler processes, waits while no scheduler is running, and starts another process against the same files. It removes the temporary files when finished.

import json
from contextlib import closing
from pathlib import Path
import sqlite3
import subprocess
import sys
from tempfile import TemporaryDirectory
import time


def call(root, mode, seconds=3):
    result = subprocess.run(
        [sys.executable, str(Path(__file__).with_name("scheduler_service.py")), mode,
         "--root", str(root), "--seconds", str(seconds)],
        capture_output=True, text=True, check=True, timeout=20,
        creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
    )
    return [json.loads(line) for line in result.stdout.splitlines()]


def main():
    with TemporaryDirectory(prefix="apscheduler-demo-") as directory:
        root = Path(directory)
        initial = call(root, "init")
        first = call(root, "run")
        time.sleep(3)
        second = call(root, "run", seconds=1)
        with closing(sqlite3.connect(root / "reports.sqlite")) as db:
            report = db.execute("SELECT batch, total FROM reports").fetchall()
            attempts = db.execute("SELECT count(*) FROM attempts").fetchone()[0]
        print(json.dumps({"processes": [initial[0]["pid"], first[0]["pid"], second[0]["pid"]],
                          "preserved_on_restart": not second[0]["changed"],
                          "reports": report, "completed_attempts": attempts,
                          "restart_events": second[1]["events"]}, indent=2))


if __name__ == "__main__":
    main()

The recorded run used three distinct process IDs and reported preserved_on_restart: true. It retained one report, ["demo-batch", 55], with three completed attempts. The restarted process emitted an execution event. Attempt counts depend on timing; the useful checks are that the schedule was retained, due work ran, and repeated calls did not create extra report rows.

To inspect files yourself, run python scheduler_service.py init, followed by python scheduler_service.py run. These commands keep data in scheduler-demo. Run the latter again after a pause to observe recovery. The default run lasts six seconds; this finite runner is designed for inspection and does not install a background operating-system service.

Use python scheduler_service.py replace --interval 10 only when you intend to replace the schedule. An --interval value supplied during ordinary startup does not change an existing job in this example. Make configuration changes an explicit operation rather than silently resetting timing on every restart.

Choose missed-run and overlap policies separately

Three settings in the example answer different questions. misfire_grace_time=60 permits a due execution to start up to 60 seconds late. coalesce=True combines a backlog of due times into one execution. max_instances=1 limits concurrent instances of that job within this scheduler.

We tested coalescing with five controlled past-due times. With it enabled, the job body ran once; with it disabled, the body ran five times. A separate job outside a one-second grace period emitted a missed event without running. Another within its grace period executed. These results match the policies described in the 3.x user guide.

The overlap test scheduled a slow job more frequently than it could finish. Its actual peak concurrency stayed at one, two calls completed, and nine scheduled attempts emitted overlap-skip events. Those skipped attempts did not become a queue to replay after the running call finished. Increasing the grace period is not a replacement for deciding how much concurrent work the application should accept.

For a refresh of current state, one catch-up call may be enough. For a report that must exist for every business day, combining due times can lose the distinction between periods. Model the required periods and completion records explicitly. The data pipeline orchestration guide covers dependencies, retries, and recovery beyond one recurring function.

Read the validation results with their limits

The exact example passed 47 functional checks. Process restart, job writes, overlap, and graceful shutdown used real processes, files, and running jobs. Past-due timestamps were supplied deliberately for the coalescing and grace tests, so those checks did not require waiting through a long outage.

CaseObserved result
Separate initialization and restart processesOne job retained; exact next-run timestamp preserved until deliberate replacement
Overdue persistent job restored by a new processImportable function executed and wrote the expected report
Stable-ID replacement and invalid registrationReplacement kept one job; conflicting ID and non-importable lambda were rejected
Repeated business operationOne report row with total 55; separate successful-attempt records
Five controlled past-due timesOne call with coalescing; five calls without it
Grace-period boundariesExpired run emitted a missed event; eligible late run executed
Slow recurring jobPeak concurrency one; two calls completed and nine overlap events recorded
Job exception and graceful shutdownError reported without automatic one-shot retry; another job ran; shutdown waited for an active job
Timezone calculations and file cleanupUTC and named-zone results matched; SQLite files could be renamed and temporary directories removed

The main scheduler uses UTC. Separate trigger calculations checked a named Monday schedule and a 09:00 Europe/Zurich schedule in winter and summer. The local hour stayed at 09:00 while the calculated UTC hour changed from 08:00 to 07:00. These were date calculations, not tests executed during a daylight-saving transition. The cron-trigger reference explains why local clock changes need attention; named weekdays also avoid confusion over weekday numbering.

The failure test produced an error event, and an independent later job still ran. The failed one-shot job was not automatically retried. The shutdown test held an active job, confirmed that shutdown(wait=True) waited, then released it and verified the result. That wait is not a job timeout. Give the job’s own network calls and external operations appropriate deadlines.

Keep one scheduler responsible for the store

Do not start a scheduler in every web worker and point them at the same APScheduler 3.x job store. The 3.x FAQ warns that sharing the store across processes can cause duplicate or missed execution. max_instances is not a distributed lock. This example assumes one owner; it does not implement a lock that prevents an operator from starting another owner.

If work needs separate workers, delivery queues, or independent execution capacity, consider the Celery and Redis guide. Keep the schedule, job delivery, and business completion records distinct. A persistent schedule alone does not guarantee exactly-once execution or recovery from every crash.

For continuous operation, supervise the dedicated scheduler process, plan a graceful stop, back up persistent data, and monitor execution, error, missed-run, and overlap events. The Python logging guide helps organize those records. Review library logs as well as your listener output before deciding which fields are safe to retain.

CPU instances from Compute with Hivenet can host a scheduler and application workers you operate. You remain responsible for the process lifecycle, permissions, persistent storage, backups, job behavior, and recovery. This example has not tested a Linux service, a cloud deployment, forced process loss, database failure, or distributed coordination.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.