Skip to content

Add an optional per-schedule timezone to the cron plugin - #99

Merged
TkTech merged 2 commits into
TkTech:26_uxfrom
luca-montaigut:cron-timezone-upstream
Oct 6, 2026
Merged

TkTech merged 2 commits into
TkTech:26_uxfrom
luca-montaigut:cron-timezone-upstream

Conversation

@luca-montaigut

@luca-montaigut luca-montaigut commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Adds an optional timezone to cron schedules, so 0 9 * * * can mean 09:00 in Paris all year round instead of 07:00 or 08:00 UTC depending on the season.

await Cron.schedule(
    chancy,
    "0 9 * * *",
    job.with_unique_key("morning_report"),
    timezone=ZoneInfo("Europe/Paris"),
)

The plugin docstring currently rules timezones out because of daylight saving time. This PR defines and tests what happens around DST, so the feature doesn't have to be avoided because of it.

Changes

  • Cron.schedule() takes timezone: ZoneInfo, UTC by default. Existing calls behave exactly as before.
  • A new cron migration adds timezone TEXT NOT NULL DEFAULT 'Etc/UTC', so existing schedules keep running in UTC.
  • next_run is computed in the schedule's timezone, both in schedule() and in the polling loop, and is still stored as a TIMESTAMPTZ.
  • The timezone is exposed by get_schedules(), the API, the Django model and admin (restricted to IANA names), and the dashboard.
  • The dashboard timeline used the browser's timezone to compute upcoming runs, so a UTC schedule was drawn off by the browser's offset. It now uses each schedule's timezone.
  • The cron extra depends on tzdata, for hosts without an IANA database (Windows, slim images).

Daylight saving time

Europe/Paris Fixed-time job (30 2 * * *) Wildcard job (*/30 * * * *)
Spring, skipped 02:00-03:00 runs once, at 03:00 runs at the times that exist
Autumn, repeated 02:00-03:00 runs once, in the first pass follows real time, runs in both passes

A job is fixed-time when neither its minute nor its hour field starts with * (macros are expanded first, so @daily is fixed-time and @hourly a wildcard). Plain croniter already gives this table except for the autumn fixed-time case, where it ran the job twice. That's the only DST-specific code.

The rules, and the remaining limitations, are documented in the plugin docstring.

Tests

  • tests/plugins/test_cron_dst.py (new) replays the polling loop minute by minute across both 2026 Paris transitions and pins the exact runs for fixed-time, wildcard and macro expressions.
  • tests/plugins/test_cron.py covers storage, the UTC default, rescheduling, the migration of existing rows, and the polling loop running schedules in several timezones at once.
  • The full suite passes locally on Postgres 17.

Cron.schedule() takes a timezone (a ZoneInfo, UTC by default) in which
the cron expression is evaluated, both when scheduling and in the
polling loop. It is stored by a new cron migration as NOT NULL DEFAULT
'Etc/UTC', so existing schedules keep running in UTC.

Around daylight saving time transitions, a fixed-time job (neither
minute nor hour is a wildcard) runs once, and a wildcard job follows
real time. tests/plugins/test_cron_dst.py pins this by replaying the
polling loop across both transitions.

The timezone is exposed by get_schedules(), the API, the Django model
(restricted to IANA names) and the dashboard, whose timeline now
evaluates each expression in its schedule's timezone rather than the
browser's. The cron extra depends on tzdata for hosts without an IANA
database.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@luca-montaigut
luca-montaigut marked this pull request as ready for review September 30, 2026 10:39
@TkTech

TkTech commented Sep 30, 2026

Copy link
Copy Markdown
Owner

I like the feature in general, but in hindsight I realize the docstring wasn't clear enough. The issues aren't in Chancy, but in the underlying croniter library itself - https://github.com/pallets-eco/croniter/issues?q=is%3Aissue+timezone. Over the years timezone + DST has broken in weird ways many, many times unfortunately.

Timezonse are annoyingly complex. For example, the comments in the PR are already wrong just from a glance - not all DST changes are an hour. Australia/Lord_Howe is 30 minutes.

@TkTech
TkTech requested a balanced review from Copilot October 1, 2026 14:30
@TkTech TkTech added the enhancement New feature or request label Oct 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Django currently offers a host-specific timezone key that can stop cron polling on workers using a different timezone database.

Review effort: Balanced
Findings: 1 High severity

Open (1)
What changed in this PR

Adds per-schedule timezone support to the cron plugin, including DST behavior, persistence, Django integration, and dashboard display.

Changes:

  • Evaluates and stores schedules using individual IANA timezones.
  • Defines and tests DST transition behavior.
  • Exposes timezone data through Django, API, and dashboard interfaces.
File Description
tests/​plugins/​test_cron.py Tests timezone persistence, migration, and polling.
tests/​plugins/​test_cron_dst.py Tests spring and autumn DST behavior.
tests/​contrib/​django/​test_models.py Tests timezone choice validation.
tests/​contrib/​django/​settings.py Enables the cron Django app in tests.
README.md Advertises timezone support.
pyproject.toml Adds tzdata to the cron extra.
CHANGELOG.md Documents the new feature and migration.
chancy/​plugins/​cron/​migrations/​v3.py Adds the timezone database column.
chancy/​plugins/​cron/​django/​models.py Adds timezone choices to the ORM model.
chancy/​plugins/​cron/​django/​admin.py Displays timezones in the admin.
chancy/​plugins/​cron/​__init__.py Implements timezone-aware scheduling and DST handling.
chancy/​plugins/​api/​ui/​src/​utils/​timeline.ts Evaluates timeline entries in schedule timezones.
chancy/​plugins/​api/​ui/​src/​pages/​Crons.tsx Displays schedule timezones.
chancy/​plugins/​api/​ui/​src/​hooks/​useCrons.tsx Adds timezone to the API type.
chancy/​plugins/​api/​ui/​src/​components/​cron/​CronTimeline.tsx Passes timezones into timeline calculations.
chancy/​plugins/​api/​ui/​src/​components/​cron/​CronDetailView.tsx Shows timezone details.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread chancy/plugins/cron/django/models.py Outdated

PREFIX = getattr(settings, "CHANCY_PREFIX", "chancy_")

TIMEZONE_CHOICES = [(tz, tz) for tz in sorted(available_timezones())]
@codecov

codecov Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.00%. Comparing base (7e81544) to head (dbce608).
⚠️ Report is 2 commits behind head on 26_ux.

Additional details and impacted files
@@            Coverage Diff             @@
##            26_ux      #99      +/-   ##
==========================================
+ Coverage   67.44%   68.00%   +0.55%     
==========================================
  Files          62       65       +3     
  Lines        3772     3822      +50     
==========================================
+ Hits         2544     2599      +55     
+ Misses       1228     1223       -5     
Flag Coverage Δ
unittests 68.00% <100.00%> (+0.55%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

The documentation assumed every DST change skips or repeats one hour at
02:00, which only holds for timezones like Europe/Paris. Describe the
rules in terms of the skipped and repeated periods, and test them on
Australia/Lord_Howe (30-minute shift), Antarctica/Troll (2-hour shift)
and America/Santiago (change at midnight).

Also leave "localtime" out of the Django timezone choices: some systems
list it, but it is the host's own timezone rather than a portable IANA
name.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@luca-montaigut

Copy link
Copy Markdown
Contributor Author

Thanks, that's a fair concern. Since this PR leans on croniter for almost everything, the safety net has to be tests rather than trust in croniter.

You're right about Lord_Howe: the docs assumed a one-hour change at 02:00. In 8a341c8 they describe the rules in terms of the skipped and repeated period, whatever its length or time, and tests/plugins/test_cron_dst.py now checks them on Australia/Lord_Howe (30-minute shift), Antarctica/Troll (2-hour shift) and America/Santiago (change at midnight), in both directions, alongside Europe/Paris.

Each case replays the polling loop minute by minute across the transition and pins the exact list of runs. So if a croniter release changes its timezone behaviour, CI fails on the affected case instead of schedules silently shifting. The only DST-specific code on our side is the one that stops a fixed-time job from running twice in a repeated period; everything else in the table is croniter's own behaviour, now under test.

I also took Copilot's point: localtime is excluded from the Django choices.

Out of curiosity, why croniter rather than another cron library?

@TkTech

TkTech commented Oct 2, 2026

Copy link
Copy Markdown
Owner

Out of curiosity, why croniter rather than another cron library?

Best of the worst, and doesn't pull in a bunch of dependencies, but happy to hear alternatives if there's anything new on the block.

@luca-montaigut

Copy link
Copy Markdown
Contributor Author

happy to hear alternatives if there's anything new on the block

cronsim, by the author of Healthchecks.io, looks like a good candidate. I ran it through the same DST cases as this PR's tests:

Pros

  • No dependencies (croniter pulls in python-dateutil).
  • Built to match Debian's cron, DST included. It passes these cases natively, including the autumn fixed-time case where croniter runs the job twice. This PR's DST-specific code would go away.

Cons

  • A single maintainer, where croniter now has pallets-eco behind it.
  • Syntax coverage versus croniter is unverified (e.g. H hashing, the year field). An expression already stored in the database that it can't parse would stop the cron plugin after an upgrade, so a switch would need that inventory first.
  • One edge case differs: a wildcard job restricted to a skipped period (*/15 2 * * * in spring) doesn't run at all, where croniter runs it once at the end of the period.

That said, this PR covers what we need with croniter, and the behaviour is pinned by the DST tests, so there's no urgency to migrate. If you're interested, I'd keep it as a separate PR, and the DST test suite would show exactly what changes.

Would it be possible to get timezone support into the 0.26 release?

@TkTech
TkTech merged commit 9e8d2b3 into TkTech:26_ux Oct 6, 2026
25 checks passed
@TkTech

TkTech commented Oct 7, 2026

Copy link
Copy Markdown
Owner

This was pulled in with some additional work - as is, it crashes on croniter 6.0.0 which was our lower bounds due to a DST behavior change in 6.2.4, and some fixes for double invokes around a time change.

Still doesn't work right with Howe, but turns out that's a croniter bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants