Task Scheduling
Define your recurring commands, jobs, and callables in code and drive them with a single cron entry.
Instead of scattering cron entries across servers, Alata lets you define your entire recurring-task schedule in one Python file, with a fluent API for frequencies and constraints. A single OS-level cron entry runs ./alata schedule:run every minute; the scheduler evaluates which events are due and executes them.
Defining the schedule
The schedule lives in your application's console kernel, in the schedule() method:
from alata.console.kernel import ConsoleKernel
from alata.console.scheduling.schedule import Schedule
class AppKernel(ConsoleKernel):
def schedule(self, schedule: Schedule):
schedule.command("queue:prune-orphans").hourly()
schedule.job("reports:generate").daily_at("02:00").on_one_server()
schedule.call(refresh_exchange_rates).every_thirty_minutes()The scaffolded project ships this file with a working example already in place — the framework schedules queue:prune-orphans hourly to keep the queue healthy.
What you can schedule
The Schedule registry offers three event types.
Console commands
schedule.command() runs any ./alata command in a subprocess:
schedule.command("migrate:status").daily()
schedule.command("horizon:snapshot").every_five_minutes()Command events support output redirection:
schedule.command("report:send ops@example.com") \
.daily_at("06:00") \
.send_output_to("storage/logs/report.log")
# Or append instead of overwrite:
schedule.command("db:status").hourly().append_output_to("storage/logs/db.log")Queued jobs
schedule.job() dispatches a registered queue task to the broker — a queue worker executes it when using the database, Redis, or SQS connection. The sync connection runs the job inline:
schedule.job("reports:generate").daily_at("02:00")
# With arguments and a queue override
schedule.job("reports:generate", user_id="abc", queue="reports").hourly()
# Or set the queue fluently
schedule.job("emails:digest").daily().on_queue("emails")You can also pass a ShouldQueue class directly:
from app.jobs.generate_report import GenerateReport
schedule.job(GenerateReport, user_id=42).daily_at("02:00").on_queue("reports")Jobs referenced by name are discovered using the application's queue configuration. An unknown task fails the event and is logged.
Callables
schedule.call() runs any Python callable in-process — sync or async:
async def refresh_exchange_rates():
...
schedule.call(refresh_exchange_rates).every_thirty_minutes()
schedule.call(lambda: print("heartbeat")).every_five_minutes()
schedule.call(cleanup, days=30).weekly().description("Prune old audit rows")Use .description("...") to give any event a readable name for schedule:list and log output.
Frequencies
Every event defaults to * * * * * (every minute) until you narrow it. All helpers return the event, so they chain.
Anchors and modifiers
Frequency helpers come in two kinds, and the difference decides what chaining does:
- Anchors set the whole expression. Anything you spliced before them is replaced:
cron(),weekly_on(),monthly_on(),twice_monthly(),yearly_on(), and the four zero-argument anchorsweekly(),monthly(),quarterly(),yearly(). - Modifiers splice individual cron fields and leave the rest alone: the
every_*helpers,hourly*(),daily(),at()/daily_at(),twice_daily*()(minute + hour), the day-of-week helpers (weekday field), anddays_of_month(),last_day_of_month(),quarterly_on()(day/month fields).
Modifiers compose in either order. Anchors do not compose — they reset.
The four zero-argument anchors make one exception: a time set earlier with at() / daily_at() is carried over instead of being reset to midnight.
schedule.command("report:send").at("03:00").weekly() # 00 03 * * 0 — time kept
schedule.command("report:send").weekly() # 0 0 * * 0 — midnight default
schedule.command("report:send").weekly_on(0, "03:00") # 00 03 * * 0 — same thing, explicit
schedule.command("report:send").at("03:00").cron("0 4 * * *") # 0 4 * * * — cron() wins outrightThe *_on(...) anchors take their time as an argument and always use it. cron() discards any remembered time — the raw expression is exactly what runs.
Minute-level and above
| Method | Cron |
|---|---|
every_minute() | * * * * * |
every_two_minutes() / every_three_minutes() / every_four_minutes() | */2, */3, */4 |
every_five_minutes() / every_ten_minutes() / every_fifteen_minutes() / every_thirty_minutes() | */5, */10, */15, */30 |
hourly() | 0 * * * * |
hourly_at(17) or hourly_at([0, 30]) | at given minute(s) |
every_odd_hour(minute=0) | hours 1–23 step 2 |
every_two_hours() / every_three_hours() / every_four_hours() / every_six_hours() | */2 … */6 hours, minute arg optional |
daily() | 0 0 * * * |
daily_at("13:30") / at("13:30") | daily at a time |
twice_daily(1, 13) / twice_daily_at(1, 13, minute=30) | two hours a day |
weekly() | Sunday 00:00 |
weekly_on(1, "8:00") | given weekday and time |
monthly() | 1st at 00:00 |
monthly_on(4, "15:00") | given day and time |
twice_monthly(1, 16, "13:00") | two days a month |
last_day_of_month("12:00") | last day of the current month |
days_of_month(5, 15, 25) | specific days of the month |
quarterly() / quarterly_on(day=1, time="0:0") | first month of each quarter |
yearly() / yearly_on(month=6, day=1, time="9:00") | once a year |
cron("0 4 * * 1-5") | any raw cron expression |
Day-of-week constraints
These modify the weekday segment of whatever frequency you already set:
schedule.command("report:send").daily_at("08:00").weekdays()
schedule.command("backup:run").twice_daily(1, 13).sundays()Available: weekdays(), weekends(), mondays() through sundays(), and days(1, 3, 5) for arbitrary sets (0 = Sunday).
Chaining order doesn't matter between modifiers: time-of-day methods set only the minute/hour fields and these set only the weekday field, so mondays().at("03:00") and at("03:00").mondays() both compile to 00 03 * * 1. An anchor anywhere in the chain still resets everything before it.
Sub-minute frequencies
The scheduler supports repeating an event multiple times within its minute. When any sub-minute event is due, schedule:run stays alive until the end of the current minute and re-fires it on the configured interval:
schedule.call(poll_upstream).every_ten_seconds()Available: every_second(), every_two_seconds(), every_five_seconds(), every_ten_seconds(), every_fifteen_seconds(), every_twenty_seconds(), every_thirty_seconds(). The interval must divide 60 evenly.
Sub-minute events combine with on_one_server(): the server claim is taken once per minute, before the first run, and every repeat within that minute belongs to the server that won it. A server that loses the claim skips the whole minute rather than the first run only.
Constraints and filters
Timezone
Schedules use SCHEDULE_TIMEZONE, falling back to APP_TIMEZONE (UTC by default). timezone() overrides that default for one task:
schedule.command("report:send").daily_at("09:00").timezone("Asia/Tokyo")This timezone also controls weekday constraints, between(), unless_between(), and last_day_of_month(). The last day is evaluated for each month, including leap years. schedule:list converts the next occurrence to UTC and displays the effective timezone beside it.
At daylight-saving changes, a local time that does not exist is skipped; a time that occurs twice can run twice. Use UTC schedules or make the job idempotent when repeated local times matter. See dates and timezones for configuration and testing helpers.
Environments
Restrict an event to specific environments:
schedule.command("backup:run").daily().environments("production")Truth-test filters
when() runs the event only if a callback returns True; skip() is the inverse:
schedule.call(sync_inventory).hourly().when(lambda: feature_enabled("sync"))
schedule.call(heavy_job).daily().skip(is_black_friday)between() and unless_between() gate execution to a daily time window (they respect the event's timezone, and handle overnight windows like 22:00–06:00):
schedule.command("index:rebuild").every_thirty_minutes().unless_between("09:00", "17:00")Maintenance mode
While the application is in maintenance mode (./alata down), scheduled events are skipped. Mark critical events to run anyway:
schedule.command("backup:run").daily().even_in_maintenance_mode()Preventing overlaps
By default a long-running event can overlap with its own next execution. without_overlapping() takes a lock in the cache before running and releases it afterwards:
schedule.command("index:rebuild").every_five_minutes().without_overlapping()The lock expires automatically after 24 hours as a safety net for crashed executions; tune it (in minutes) if your task can legitimately run longer:
schedule.command("index:rebuild").every_five_minutes().without_overlapping(expires_after=10)What identifies an event
The lock key is derived from the event's stable identity: its cron expression plus what it actually runs — the command string, or the task name and its arguments, or the callback's qualified name and its arguments. Two consequences:
- Same task, different arguments, same frequency → different locks. Per-tenant jobs like
schedule.job("reports:generate", "tenant-a")andschedule.job("reports:generate", "tenant-b")never block each other. description()is not part of the key. Rewording a description leaves overlap protection exactly where it was; it never silently resets the lock mid-deploy.
Keyword-argument order doesn't matter. Two caveats worth knowing when you rely on the key:
- Arguments are rendered with
repr(). Pass plain data — an object with the default<... at 0x...>repr produces a key that changes every process. - Sibling lambdas share a qualified name, so a lambda's identity includes its source line. Schedule a named function when the key must survive edits to the schedule file.
Running on one server
When the scheduler runs on multiple servers, every server would fire every event. on_one_server() makes servers race for an atomic cache lock — the first to acquire it runs the event, the rest skip it:
schedule.job("reports:generate").daily_at("02:00").on_one_server()The lock key is scoped to the current minute (with a TTL just over one cron cycle), so consecutive minutes use distinct keys and a lock claimed late in one minute can never starve the next minute's run.
The claim is taken once per minute per event, not once per execution — so a sub-minute event that wins the claim keeps running for the rest of that minute instead of losing to its own lock on the second repeat.
Both without_overlapping() and on_one_server() are backed by the configured cache store — the scaffold defaults to a local file store. For coordination across servers, select Redis or the database store and point every server at the same backend.
Hooks
Attach callbacks around an event's execution:
schedule.command("backup:run").daily() \
.before(lambda: notify("backup starting")) \
.after(lambda: notify("backup attempt finished")) \
.on_success(lambda: notify("backup ok")) \
.on_failure(lambda: notify("backup FAILED"))then() is an alias for after(). Success and failure are decided by the event's exit code (0 = success).
The scheduler also fires framework events for each execution: ScheduledTaskStarting, ScheduledTaskFinished (with duration), ScheduledTaskSkipped (with the reason), and ScheduledTaskFailed (with the exit code) — all importable from alata.events.scheduling. Listen to them for centralized monitoring.
Running the scheduler
Add a single cron entry on your server that invokes schedule:run every minute:
* * * * * cd /path/to/project && /path/to/project/.venv/bin/python alata schedule:run >> /dev/null 2>&1Use the absolute path to your application's Python interpreter; cron does not inherit your shell's activated environment.
Each invocation evaluates all registered events, executes the due ones (one-shot events run concurrently), and exits — unless sub-minute events are due, in which case it stays alive for the remainder of the minute.
When one event is broken
A single bad definition never takes the schedule down with it:
- An event whose expression can't be evaluated is logged and skipped; every other due event still runs.
- If the
schedule()method itself raises — a constraint applied to an expression that can't hold it, say — the failure is logged loudly and the events registered before it still run. Events defined after the failing line were never registered, and the log says so.
Both commands report this, so schedule:list is the fastest way to see what's actually registered. Broken expressions show up there as INVALID EXPRESSION in the next-due column.
Cron nicknames (@daily, @hourly, @weekly, @monthly, @yearly) are valid input to cron() and expand to their five-field form when you splice a constraint onto them:
schedule.command("report:send").cron("@daily").mondays() # 0 0 * * 1@reboot has no periodic equivalent — applying a constraint to it raises InvalidScheduleExpressionError naming the event, rather than failing deep inside the DSL.
Inspecting the schedule
schedule:list prints every registered event with its cron expression, next due time, and constraints:
./alata schedule:list
Expression Description Next Due (UTC) Constraints
----------- ----------------------------- ---------------- -----------
0 * * * * ./alata queue:prune-orphans 2026-07-28 15:00 tz:UTC
0 2 * * * Job: reports:generate 2026-07-29 02:00 one-server, tz:UTCThe constraints column flags no-overlap, one-server, and tz:<zone> so you can verify locking and timezone behavior at a glance.