Skip to main content

xtr-scheduler

Recurring messages on xtr-messenger: cron and periodic triggers, catch-up after downtime, locks and saved state across restarts.

python 3.14+ asyncio typed license MIT

Why?

"Every night at three" and "every ten minutes" sound simple until a worker restarts at 02:59, two replicas both think it is their turn, or the machine was off for an hour and nobody knows which runs were missed.

A schedule here is a set of recurring messages — a message and when to send it. A scheduler transport turns the schedule into messages as they fall due, and a messenger worker consumes it like any other transport: each message is handled there, or sent on to wherever routing puts it — a RabbitMQ queue and its worker pool, say.

  • ⏱️ At least once, in order — every message is recorded as sent before the next is produced, so in the ordinary course nothing goes twice and a restarted worker resumes where the last one stopped; a crash between sending a run and recording it sends that run again.
  • 🔁 Catch-up — after downtime every missed run is sent, oldest first, or only the latest of each when the schedule asks.
  • 🔒 One sender — give a schedule an xtr-lock lock and only the process holding it sends; give it an xtr-cache pool and its progress survives restarts.
  • 🧭 Cron, intervals, or your own — hashed cron (#daily) spreads tasks across the hour; jitter spreads a fleet; triggers are a one-method protocol.
  • 🧪 Testable in no time — time comes from xtr-clock, so a test freezes it and steps through a day instantly.

Install

uv add "xtr-scheduler[cron]"                            # + cron expressions
uv add "xtr-scheduler[cron]" xtr-dependency-injection   # + the container, for the SchedulerBundle
uv add xtr-console                                      # beside it: the debug:scheduler console command
Extra Brings For
(none) xtr-messenger, xtr-serializer, xtr-clock, xtr-lock, xtr-cache-contracts, xtr-event-dispatcher, xtr-event-dispatcher-contracts, xtr-service-contracts, pydantic Intervals, the transport, events
cron croniter RecurringMessage.cron(...) and @as_cron_task

No xtr package is an extra, and the container is not a dependency: the SchedulerBundle is used when xtr-dependency-injection is installed beside the package — see Kernel / bundle — and schedules, the transport and Scheduler work without it, as the Quick start shows. With the container in place, xtr-console brings debug:scheduler, and xtr-cache, with its bundle active, a scheduler pool for a schedule to keep its state in.

Requires Python 3.14.4+.

Quick start

from xtr_messenger import MessageBusConfig, TransportConfig, WorkerFactory
from xtr_scheduler import RecurringMessage, Schedule
from xtr_scheduler.messenger import SchedulerTransportFactory

schedule = Schedule(
    RecurringMessage.cron("0 3 * * *", PurgeSessions(), timezone="Europe/Bucharest"),
    RecurringMessage.every("10 minutes", RefreshRates()),
)

config = MessageBusConfig(transports={"scheduler": TransportConfig("schedule://default")})
factories = [SchedulerTransportFactory({"default": schedule})]

await WorkerFactory(config, factories).worker(["scheduler"]).run()

The worker handles each message as it falls due, with whatever @as_message_handler declares for its type. schedule://default names the schedule.

Sending runs on

A worker consuming a schedule is one process. To have the runs handled on your worker pool instead, wrap the message in a RedispatchMessage — it is dispatched again, through routing:

from xtr_messenger import RedispatchMessage

RecurringMessage.every(
    "1 hour", RedispatchMessage(BuildReport())
)  # where routing sends BuildReport
RecurringMessage.every("1 hour", RedispatchMessage(BuildReport(), "reports"))  # to "reports" only

schedule://default?use_messenger_routing=true does this for every message of the schedule. The message arrives carrying a ScheduledStamp — which schedule, which run — on whichever worker handles it. Its dates cross a broker as they left: a run in a named zone keeps the zone and its fold, so the two 03:00 runs of the night the clocks go back stay two runs.

Recurring messages

Build Runs
RecurringMessage.every(60, msg) every 60 seconds
RecurringMessage.every("10 minutes", msg) every 10 minutes — second, minute, hour, day, week, fortnight, month, year, plural or not
RecurringMessage.every("PT1H", msg) ISO 8601 durations, converted to seconds
RecurringMessage.every(timedelta(hours=1), msg) a timedelta
RecurringMessage.cron("0 3 * * *", msg, timezone=...) a cron expression, on the clock of timezone — the clock's own zone when omitted
RecurringMessage.trigger(trigger, msg) any TriggerInterface
.with_jitter(30) each run delayed at random by up to 30 seconds

Seconds, minutes and hours are exact: runs fall exactly that far apart. Days, weeks, months and years follow the calendar — "every day" at 09:00 stays at 09:00 across a clock change, and "every month" from the 31st runs on the last day of shorter months. every(..., from_=..., until=...) bounds an interval; left without from_, it counts from when the schedule first ran.

Hashed cron puts # where a value would go: "# # * * *" is once a day at a minute and hour picked for that message, from its string form — the same pick in every process, a different one per message, so a hundred daily tasks do not all start at midnight. #(0-5) picks within a range, and #hourly, #daily, #weekly, #monthly, #yearly and #midnight are shorthands.

A message may be a MessageProviderInterface instead, deciding the messages of each run — CallbackMessageProvider(lambda context: [Invoice(t) for t in active_tenants()]).

Triggers are strict: the next run is always strictly after the one asked about, or None to stop. CallbackTrigger, ExcludeTimeTrigger (skip a window) and JitterTrigger compose with the rest.

A schedule's behaviour

schedule = (
    Schedule(...)
    .lock(lock_factory.create_lock("schedule-default"))  # only the holder sends
    .stateful(cache_pool)  # progress survives restarts
    .process_only_last_missed_run()  # after downtime, the latest run only
)
No cache With .stateful(pool)
No lock Every process sends every run; a restart starts from now Every process sends; a restart resumes
With .lock(lock) One process sends; another taking over starts from now One process sends; another taking over resumes

Between runs the lock is kept until the next one is due. A worker that stops gives it back, so the next process takes over at once; one that crashes leaves it to run out.

While a batch runs, the lock is refreshed before each message is handed on and before the batch is saved — a lock without a lifetime is asked whether it is still held. A batch whose lock was lost meanwhile stops there, quietly and without saving: whoever holds the lock now sends what is left. A single message held longer than the lock's lifetime may still be sent again by the process taking over — delivery is at least once — so give the lock a lifetime longer than a message takes.

A pool that fails to save stops the schedule with SchedulerRuntimeError rather than carrying on: going on would send every run again after a restart, or nothing at all.

Adding or removing messages while the schedule runs is safe — what already ran is not sent again.

Events

schedule.before(lambda event: event.should_cancel(not maintenance_window_open()))
schedule.after(lambda event: metrics.record(event.context.id, event.result))
schedule.on_failure(lambda event: alert(event.message, event.error))

PreRunEvent (a listener may cancel the run — the worker then skips the message), PostRunEvent (with what handling returned) and FailureEvent. They come from the worker that handles the message, through DispatchSchedulerEventListener subscribed to the messenger's worker events — the application's dispatcher hears them first, then the schedule's own listeners. A run redispatched through routing is announced once, by the worker that handles it where it lands: one sent to sync://, or to a transport no worker with the listener consumes, is not announced.

Declaring tasks

A class or function can be a task without writing a schedule:

from xtr_scheduler.decorator import as_cron_task, as_periodic_task, as_schedule


@as_cron_task("0 3 * * *", timezone="Europe/Bucharest")
async def purge_sessions() -> None: ...


@as_periodic_task("10 minutes", jitter=30, transports="jobs")
class RefreshRates:
    async def __call__(self) -> None: ...


class Maintenance:
    @as_cron_task("#daily")
    async def vacuum(self) -> None: ...

    @as_cron_task("#weekly", arguments=["full"])
    async def reindex(self, mode: str) -> None: ...

Each run sends a ServiceCallMessage naming the target, handled by calling it. schedule= picks the schedule ("default" otherwise), method= the method of a class, arguments= JSON values to call it with, and transports= sends the runs there to be handled rather than where the schedule is consumed. Stack the decorators for several runs.

@as_schedule("name") declares a class providing a whole schedule; tasks on the same name join it.

Without a container, schedule://<name> still serves the declared schedules as discovery finds the transport, each provider built with no arguments. Handling a run is separate: the ServiceCallMessageHandler takes its task targets and its per-target method allow-list as required arguments, so without a container the caller wires it — ServiceCallMessageHandler( declared_task_targets(), TaskMethods(declared_task_methods())) — rather than it building bare.

Use in an application

Everything adding this package to an application on xtr-dependency-injection takes — and, read backwards, what removing it undoes.

  • Install — uv add "xtr-scheduler[cron]" xtr-dependency-injection: the bundle needs the container installed beside it, never as an extra. Install xtr-console beside it for debug:scheduler, and xtr-cache for the scheduler cache pool a schedule keeps its state in.
  • Recipe — uv run xtr-recipes recipes:sync does the Activate and Configure steps below: it lists SchedulerBundle, which brings the messenger bundle with it, and writes <app>/config/packages/scheduler.py with the bundle's own defaults. There is no environment or ignore line to write; it prints the steps to declare your recurring work and copy the starter schedule, which a recipe cannot make for you.
  • Activate — SchedulerBundle: {"all": True} in BUNDLES in <app>/config/bundles.py, imported from xtr_scheduler.bundle.
  • Brings along — the messenger bundle always, because schedules are sent through it; the event dispatcher and console bundles, when those packages are installed.
  • Configure — optional: the recipe writes <app>/config/packages/scheduler.py holding the defaults, scheduled messages handled by the worker consuming the schedule, and that is where the handover is changed. The schedule itself is declared beside the tasks: with no configuration every task joins a plain default schedule, which keeps no state and takes no lock. For one that resumes after a restart and sends each run once, copy a starter schedule into <app>/schedule.py and activate the cache and lock bundles it needs.
  • Environment — nothing.
  • Ignore — nothing.
  • Run — a worker is <script> messenger:consume scheduler_default.
  • Remove — drop the BUNDLES entry, delete <app>/schedule.py and every @as_cron_task / @as_periodic_task; uv run xtr-recipes recipes:remove xtr-scheduler deletes <app>/config/packages/scheduler.py, unless you edited it, in which case it is moved aside to scheduler.py.removed. Then uv remove xtr-scheduler.
  • Check — debug:scheduler lists each schedule with every message's next run.

Kernel / bundle

With xtr-dependency-injection installed beside the package — it is not a dependency, and nothing outside xtr_scheduler.bundle imports it — list the bundle:

# app/config/bundles.py
from xtr_scheduler.bundle import SchedulerBundle

BUNDLES = {SchedulerBundle: {"all": True}}

The bundle brings the messenger bundle with it. Every schedule and task its scan finds is built by the container with its dependencies — and a function task may ask for services with Injected[...]. Each schedule becomes consumable as scheduler_<name> without configuring a transport:

uv run python -m app.console messenger:consume scheduler_default

Configure scheduler_<name> yourself — TransportConfig("schedule://default?use_messenger_routing=true") — and yours is used instead. SchedulerConfig(use_messenger_routing=True) sets it for all of them. The transport asks for due runs once a second, so a run starts up to a second after it falls due; nothing is skipped, as a late run is still sent.

A starter schedule

Tasks alone need no schedule class: the bundle gathers them into a plain Schedule per name. A plain schedule keeps no state and takes no lock, though — a restarted worker starts from now, forgetting what it missed, and two workers both send every run. To choose, write the schedule the tasks join; this is a good first one to copy into the application:

# app/schedule.py
from typing import Annotated, override

from xtr_cache_contracts import CacheInterface
from xtr_dependency_injection import Target
from xtr_lock import LockFactory
from xtr_scheduler import Schedule, ScheduleProviderInterface
from xtr_scheduler.decorator import as_schedule


@as_schedule()  # "default" — every task not naming a schedule joins this one
class AppSchedule(ScheduleProviderInterface):
    def __init__(
        self,
        cache: Annotated[CacheInterface, Target("scheduler")],
        locks: LockFactory,
    ) -> None:
        self._schedule = (
            Schedule()  # add recurring messages of your own here
            .stateful(cache)  # a restart resumes, sending what was missed
            .process_only_last_missed_run()  # ...only the latest run of each, though
            .lock(locks.create_lock("scheduler-default"))  # one worker sends, however many run
        )

    @override
    def get_schedule(self) -> Schedule:
        return self._schedule

The scheduler pool it asks for exists when the cache bundle is active: the scheduler bundle adds it on the app pool's adapter, under a namespace of its own, so checkpoints never mix with the application's values and cache:pool:clear scheduler clears them alone. Configure a scheduler pool yourself — CacheConfig(pools={"scheduler": "redis://…"}) — and yours is used instead. Nothing uses the pool on its own. LockFactory comes from the lock bundle: its default resource keeps file locks, enough for workers on one machine; give it a Redis store for several.

env="prod" on a task keeps it to those environments, the way @when does for a service; its schedule stays, empty if nothing else is on it, so a worker can be started for it anywhere. With the event dispatcher bundle active, runs are announced; with the console bundle, debug:scheduler lists each schedule with every message's next run:

┌───────────────────────────────────┬─────────────────┬───────────────────────────┬─────────────┐
│ Trigger                           │ Provider        │ Next Run On               │ Next Run In │
├───────────────────────────────────┼─────────────────┼───────────────────────────┼─────────────┤
│ every 60 seconds                  │ Named (ping)    │ 2026-01-01T00:01:00+00:00 │ 1 min       │
│ 0 3 * * * with 0-30 second jitter │ Named (nightly) │ 2026-01-01T03:00:27+00:00 │ 3 h, 27 s   │
└───────────────────────────────────┴─────────────────┴───────────────────────────┴─────────────┘

--date computes from another date, --all shows messages that never run again, --sort orders by next run. A stateful schedule is listed from where its saved state says it got to.

Without a message bus

Scheduler runs schedules in-process, handing each message to a handler for its exact type:

from xtr_scheduler.scheduler import Scheduler

scheduler = Scheduler({PurgeSessions: purge}, [schedule], event_dispatcher=events)
await scheduler.run()  # until scheduler.stop()

With a dispatcher, a FailureEvent listener may ignore an error rather than let it stop the run. When run() returns, however it returns, every schedule's lock is handed back, so another process takes over at once; await scheduler.close() does the same for a scheduler that was never run.

Known limitations

  • Cron expressions are read by croniter 6: a clock change that is not a whole hour can shift a match, and stepped ranges that wrap around are read as croniter reads them.
  • Interval strings take one unit — "90 minutes", not "1 hour 30 minutes".
  • A RedispatchMessage holds an envelope and lives in the process that creates it; the message inside is what crosses a transport.
  • A recurring message's id is built from the data its message holds, written as JSON with sorted keys. A set or frozenset inside the message is written in the order the set keeps it, which for strings changes from one process to the next, and so does the id — hold a sorted tuple instead. A message the serializer refuses to carry — a naive datetime, a time in the hour the clocks repeat, a value of another type than its field declares — is still written for its id, as pydantic writes it to JSON. Only a message holding something with no JSON form at all, a callable or a lock, is told apart by its class alone: two of one class on one trigger in one schedule are refused as duplicates — wrap each in a StaticMessageProvider([message], "<id>") to name it.

Errors

Everything the library raises derives from SchedulerError: InvalidArgumentError (a value it cannot use — an interval, a date, an unknown schedule), SchedulerLogicError (a trigger that does not move forward, a message added twice, a transport asked to send) and SchedulerRuntimeError (state that could not be saved).

Upgrading

What changes for an application moving to 7.0, and how to keep the old behaviour where that is still possible: Upgrading to 7.0.

Development

Developed in the python-xtr monorepo, under packages/xtr-scheduler; run the commands below from there. The python-xtr-scheduler repository is a read-only copy, so send issues and pull requests to the monorepo.

uv sync
uv run ruff check && uv run ruff format --check && uv run basedpyright && uv run ty check && uv run pytest

License

MIT — see LICENSE.

Metadata

Release files for xtr-scheduler 7.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xtr-scheduler 7.1.0
File Size Uploaded Provenance Actions
xtr_scheduler-7.1.0.tar.gz 73.6 kB With provenance Details for xtr_scheduler-7.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xtr-scheduler 7.1.0
File Interpreter ABI Platform Actions
xtr_scheduler-7.1.0-py3-none-any.whl Python 3 none any Details for xtr_scheduler-7.1.0-py3-none-any.whl

Total release size: 173.5 kB

Release files / xtr_scheduler-7.1.0.tar.gz

Download URL xtr_scheduler-7.1.0.tar.gz
Size 73.6 kB
Tags Source
SHA-256 checksum
How to use checksums
cf7ef8179a378703133cd88ab1f60b9e186b09072e97f60c92c04451c0d4dfb0
BLAKE2b-256 checksum
How to use checksums
be3afbe8d2793523d05ada5c29e124fa081d4377aabc986f9cb0b07865678ee4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / xtr_scheduler-7.1.0-py3-none-any.whl

Download URL xtr_scheduler-7.1.0-py3-none-any.whl
Size 99.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9114f721e59b4a8b650dc069a6aa65bea6ba13083dedff0a24d12b2b27cb7de4
BLAKE2b-256 checksum
How to use checksums
efa996ab9c896bcf2a52ccf4f9978ce3eacab2042e117354f8092dcfd73c621b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for xtr-scheduler 7.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for xtr_scheduler-7.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

7.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page