Every Python team eventually reinvents a scheduler, and every homegrown scheduler eventually hurts. The script that “cron plus a shell loop” was supposed to cover gets deployed to a second server, and suddenly two workers run the same report at 2:00 AM. A restart at the wrong moment silently forgets the job that was due. A time.sleep(60) polling loop either burns CPU checking for work that is not there, or sleeps past the fire time it was supposed to hit. And the moment someone asks for “run it every month on the last business day, but in Tokyo time”, the in-house solution quietly gives up.
It is widely recognized that APScheduler is the most-used third-party answer to this problem in the Python ecosystem. What fewer developers realize is that the branch you will find on GitHub today is not the scheduler they remember from the 3.x tutorials. The default master branch — verified via git ls-remote before writing this — hosts the 4.x rewrite: a task scheduler and task queue where schedules, jobs and task definitions live as records in a pluggable data store, multiple schedulers and workers coordinate through leases, and cross-node notifications travel over separate event brokers. The README warns that the v4.0 series is a pre-release that may change incompatibly, and pyproject.toml requires Python 3.11 or newer — a modern codebase built on attrs and anyio.
This post is a source tour of that real tree: every file path, class name, line number and default value below was checked against the actual checkout. Two diagrams anchor the walk — an overview mapping the six subsystems, and a detail graph drilling into the wake-up loop, the trigger engine and the storage layer.
Overview of APScheduler on master: the exported API shapes the two scheduler flavors, which talk to triggers, pluggable data stores, executors and event brokers. Generated from the repository tree.
Reading the overview from left to right:
- AsyncScheduler, L78 is the heart: a 1229-line AnyIO implementation whose defaults say a lot —
max_concurrent_jobs=100at L117 and a 30-secondlease_durationat L129. - [process_schedules, L920](https://github.com/agronholm/apscheduler/blob/master/src/apscheduler/_schedulers/async.py#L920) is the scheduling loop: it claims up to 100 due schedules per pass at L953, applies the coalesce policy at L991 and random jitter at L998 before queueing
Jobrecords. - Trigger.next, L25 is the entire trigger contract — one iterator method plus pickle-style state hooks. Everything from cron to calendar intervals implements it.
- DataStore, L153 is the storage contract:
acquire_schedulesat L244,get_next_schedule_run_timeat L288 andacquire_jobsat L313 are the methods that make horizontal scaling possible. - SQLAlchemyDataStore.acquire_schedules, L647 claims work with a CTE guarded by
FOR UPDATE SKIP LOCKEDat L678 — the same trick database-backed job queues use to keep competing workers honest. - RedisEventBroker, L23 fans store events out to every scheduler node over pub/sub, subscribing at L91 and publishing at L128.
- RetryMixin, L38 wraps every external store operation in tenacity retries, defaulting to
stop_after_delay(60)at L29 and exponential waits between 0.5 and 20 seconds at L33. - @task decorator, L39 attaches
TaskParametersdefaults to a function under the_apscheduler_taskdefattribute defined at L17 — the 4.x replacement for 3.x’sadd_jobargument soup.
Detail view: the scheduler task group, the trigger hierarchy with the cron compiler, data stores and their serializers, executors, and the event broker family.
The wake-up loop: how the scheduler sleeps without polling
The first thing to understand about 4.x is what it does not do: it never polls. AsyncScheduler.run_until_stopped at L847 opens one AnyIO task group and starts up to three cooperative loops: a periodic cleanup loop at L872, the schedule-processing loop at L883 and the job-processing loop at L890. Which of the two worker loops actually starts depends on the SchedulerRole enum at L23 — scheduler, worker or both — so a fleet can dedicate some nodes to computing fire times and others to executing them.
Inside _process_schedules, the rhythm is: acquire a batch of due schedules, compute their next fire times, enqueue jobs, release the claims, then sleep until exactly the next fire time. The sleep is built from the data store itself: get_next_schedule_run_time at L1068 asks the store for the earliest pending fire time, and the loop parks on an anyio.Event guarded by move_on_after(wait_time) at L1081. If nothing else happens, the timer wakes it right at the due moment. If a new or updated schedule arrives earlier, the schedule_added_or_modified listener at L924 — subscribed to ScheduleAdded and ScheduleUpdated events at L944 — sets the wakeup event and the loop restarts immediately. The same pattern drives _process_jobs at L1109: the check_queue_capacity listener at L1112 wakes the loop on JobAdded or JobReleased events whenever capacity is free.
The coalesce logic is where this loop earns its keep. If a scheduler was down for three fire times, the while loop at L973 keeps calling trigger.next() to walk through the accumulated past. The CoalescePolicy enum at L117 decides what survives: earliest keeps the first missed fire time, latest (the default, set at L160 on the Schedule record) keeps only the newest, and all queues one job per missed fire time. Before each job is created, jitter is bounded so a delay can never push one fire time past the next one — the clamp lives at L1015 — and random.uniform at L1027 picks the actual offset. If the job then starts too late anyway, _run_job at L1174 compares the clock against start_deadline at L1178 and records a missed_start_deadline outcome instead of running it.
Triggers: CronTrigger’s field-by-field scan and its friends
Every timing strategy in the library is an implementation of Trigger.next(). The abstract class at L17 subclasses Iterator[datetime], so a trigger is literally an iterator of fire times, and it must also serialize itself via __getstate__/__setstate__ because triggers are stored inside schedule records and must survive a process restart.
CronTrigger at L25 is the most interesting resident. Its FIELDS_MAP at L48 fixes eight fields — year, month, day, week, day_of_week, hour, minute, second — and each field string is compiled by the classes in triggers/cron/expressions.py: AllExpression at L45 handles * and */n, RangeExpression at L81 handles ranges and steps, while WeekdayPositionExpression at L199 and LastDayOfMonthExpression at L243 implement the mon#1 and L extensions. The field compiler BaseField at L57 turns all of that into sorted sets of valid values per field, with specialized DayOfWeekField and MonthField subclasses adding extra compilers at L133 and L173.
Computing the next fire time is a classic odometer walk, implemented in CronTrigger.next at L228: start from the last fire time plus one second, scan fields from seconds upward, and when a field has no valid value left, carry into the next coarser field — the _increment_field_value calls at L244. Two details show how much DST grief this code absorbs: time_exists at L251 skips wall-clock times that a spring-forward transition deletes, and the unreleased changelog documents fixes for exactly these DST cases. The simpler triggers are refreshingly small by comparison: IntervalTrigger at L15 is plain arithmetic on start_time + k * interval, DateTrigger at L15 yields one datetime and stops, and CalendarIntervalTrigger at L15 anchors calendar-aware intervals to a fixed time of day. When you need combinations, AndTrigger at L39 accepts child fire times only if they agree within a one-second threshold (L60), giving up after max_iterations=10000 (L61) — the MaxIterationsReached exception at L76 exists precisely for pathological combinations like intersecting sparse crons.
From job stores to data stores and event brokers
The biggest conceptual shift from 3.x to 4.x is the storage split. In 3.x, “job stores” were scheduler add-ons. In 4.x there are two orthogonal contracts: the DataStore ABC at L153, which owns tasks, schedules, jobs and results, and the EventBroker ABC at L106, which carries notifications about those records. That separation is what lets a data store publish JobAdded on one node and have a worker on another node wake up — provided you pick a broker that spans nodes.
The store implementations are worth reading for their engineering discipline. SQLAlchemyDataStore at L137 spans 1273 lines because it must serve PostgreSQL, MySQL-family databases and SQLite at once: EmulatedTimestampTZ at L84 fakes timezone-aware timestamps where the engine lacks them, and the acquisition query at L647 selects due schedules ordered by fire time inside a FOR UPDATE SKIP LOCKED CTE, then flips to an UPDATE ... RETURNING path at L687 when the engine supports it. On PostgreSQL this is exactly the queue-claiming idiom used by serious job systems; the lease columns acquired_by and acquired_until at L194 are what make a crashed scheduler survivable — leases expire and another node reaps the work. MongoDBDataStore at L97 mirrors the same contract over the async pymongo API, while MemoryDataStore at L34 is the zero-dependency default when no data_store argument is given. External stores default to pickle serialization through BaseExternalDataStore at L28, with JSON and CBOR alternatives in the serializers/ package.
The broker family is the other half of the story. LocalEventBroker at L11 is 25 lines for in-process delivery, while the cross-node options match where your data already lives: Redis pub/sub in RedisEventBroker at L23, PostgreSQL LISTEN/NOTIFY on the channel apscheduler in AsyncpgEventBroker at L30 (with a psycopg twin at L34), and MQTT topics in MQTTEventBroker at L25. The Event hierarchy at L21 is a frozen-attrs class family — ScheduleAdded, JobAdded, JobReleased and friends — so consumers subscribe with typed filters via EventBroker.subscribe at L131. Execution is equally pluggable: the scheduler’s constructor preinstalls async, threadpool and processpool executors at L145, and a Qt executor at L36 delivers callbacks into a GUI event loop. The synchronous Scheduler class at L28 is not a separate implementation at all — it drives the async core through an anyio blocking portal, starting at L383.
Honest Limits
The pre-release status is the headline limitation: the README warns that v4.0 may change in backwards-incompatible ways without a migration path, so production users should weigh that against the stable 3.x series — and the layout on master will not match older tutorials, which describe the 3.x Enjoyed this post? Never miss out on future posts by following us schedulers/triggers/jobstores tree. The async core is anyio-based, so the sync Scheduler pays a portal hop on every call — fine for scripts, noticeable in tight loops. Durability is only as strong as the store you choose: MemoryDataStore and LocalEventBroker are explicitly single-process conveniences, and any multi-node promise rests on your database and broker being up. There is no built-in web UI or REST surface — observability comes from subscribing to the event classes, and administration from the store’s own query tools. Finally, custom triggers must implement state round-tripping correctly, or they will silently produce wrong fire times after a restart. None of this diminishes the design: the wake-up loop, the leased store contract and the cron compiler form one of the cleaner scheduling architectures in Python today.