Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ Each implementation gets its own virtual environment, and every one of them
runs the agent from the working tree. When you give more than one, the
driver chooses one at random for each agent it starts.

## Cron expressions

`cron-expressions.json` lists cron expressions, each with its first match after one instant, or `null` for one that the implementations must refuse. Each language's tests read it, so every `Cron` accepts the same expressions and finds the same matches.

## Scenarios

| Scenario | What it shows |
Expand Down
217 changes: 217 additions & 0 deletions conformance/cron-expressions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
{
"after": "2026-10-05T07:30:00Z",
"expressions": [
{
"expression": "0 9 * * 1-5",
"next": "2026-10-05T09:00:00Z"
},
{
"expression": "*/15 * * * *",
"next": "2026-10-05T07:45:00Z"
},
{
"expression": "0 0 1 * *",
"next": "2026-11-01T00:00:00Z"
},
{
"expression": "0 0 * * 0",
"next": "2026-10-11T00:00:00Z"
},
{
"expression": "0 0 * * 7",
"next": "2026-10-11T00:00:00Z"
},
{
"expression": "0 0 * * 0-7",
"next": "2026-10-06T00:00:00Z"
},
{
"expression": "0 0 * * MON",
"next": "2026-10-12T00:00:00Z"
},
{
"expression": "0 0 * * mon",
"next": "2026-10-12T00:00:00Z"
},
{
"expression": "0 0 * * MON-FRI",
"next": "2026-10-06T00:00:00Z"
},
{
"expression": "0 0 * * 1,3,5",
"next": "2026-10-07T00:00:00Z"
},
{
"expression": "0 0 1 JAN *",
"next": "2027-01-01T00:00:00Z"
},
{
"expression": "0 0 * JAN-MAR *",
"next": "2027-01-01T00:00:00Z"
},
{
"expression": "0 9-17/2 * * *",
"next": "2026-10-05T09:00:00Z"
},
{
"expression": "0 0 1-31/10 * *",
"next": "2026-10-11T00:00:00Z"
},
{
"expression": "0 0 1,15 * 1",
"next": "2026-10-12T00:00:00Z"
},
{
"expression": "0 0 1 * MON",
"next": "2026-10-12T00:00:00Z"
},
{
"expression": "0 0 29 2 *",
"next": "2028-02-29T00:00:00Z"
},
{
"expression": "0 0 L * *",
"next": "2026-10-31T00:00:00Z"
},
{
"expression": "0 0 LW * *",
"next": "2026-10-30T00:00:00Z"
},
{
"expression": "0 0 * * 5L",
"next": "2026-10-30T00:00:00Z"
},
{
"expression": "0 0 * * 6L",
"next": "2026-10-31T00:00:00Z"
},
{
"expression": "0 0 * * 1#2",
"next": "2026-10-12T00:00:00Z"
},
{
"expression": "0 12 * * SUN#1",
"next": "2026-11-01T12:00:00Z"
},
{
"expression": "0 0 * * 5#5",
"next": "2026-10-30T00:00:00Z"
},
{
"expression": "15 0 * * * *",
"next": "2026-10-05T08:00:15Z"
},
{
"expression": "0 15 * * * *",
"next": "2026-10-05T08:15:00Z"
},
{
"expression": "* * * * * *",
"next": "2026-10-05T07:30:01Z"
},
{
"expression": "@yearly",
"next": "2027-01-01T00:00:00Z"
},
{
"expression": "@annually",
"next": "2027-01-01T00:00:00Z"
},
{
"expression": "@monthly",
"next": "2026-11-01T00:00:00Z"
},
{
"expression": "@weekly",
"next": "2026-10-11T00:00:00Z"
},
{
"expression": "@daily",
"next": "2026-10-06T00:00:00Z"
},
{
"expression": "@midnight",
"next": "2026-10-06T00:00:00Z"
},
{
"expression": "@hourly",
"next": "2026-10-05T08:00:00Z"
},
{
"expression": "0 0 15W * *",
"next": null
},
{
"expression": "0 0 1W * *",
"next": null
},
{
"expression": "0 0 ? * *",
"next": null
},
{
"expression": "0 0 31 2 *",
"next": null
},
{
"expression": "0 0 30 2 *",
"next": null
},
{
"expression": "0 0 31 4 *",
"next": null
},
{
"expression": "0 0 * * L",
"next": null
},
{
"expression": "0 0 0 1 1 * 2027",
"next": null
},
{
"expression": "0 0 L-3 * *",
"next": null
},
{
"expression": "0 0 * * 7-1",
"next": null
},
{
"expression": "0 0 * * 5-2",
"next": null
},
{
"expression": "0 0 * * 8",
"next": null
},
{
"expression": "0 24 * * *",
"next": null
},
{
"expression": "60 * * * *",
"next": null
},
{
"expression": "*/0 * * * *",
"next": null
},
{
"expression": "* * *",
"next": null
},
{
"expression": "@reboot",
"next": null
},
{
"expression": "@every 5m",
"next": null
},
{
"expression": "every tuesday",
"next": null
}
]
}
4 changes: 3 additions & 1 deletion docs/task-behaviors.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@ async def hourly_sync(cron: Cron = Cron("0 * * * *")) -> None:
await sync_external_data()
```

Cron uses standard 5-field syntax: `minute hour day month weekday`.
Cron uses standard 5-field syntax: `minute hour day month weekday`. A sixth field at the start sets the second.

Each run's next match counts from when that run started, so a run that is still going at its next match is followed by that match's run as soon as it ends.

### Vixie Keywords

Expand Down
62 changes: 61 additions & 1 deletion python/tests/fundamentals/test_cron.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
"""Tests for Cron dependency (cron-style scheduled tasks)."""

import asyncio
import json
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import patch
from zoneinfo import ZoneInfo

import pytest
from cronsim import CronSimError

from docket import Docket, Worker
from docket import CurrentExecution, Docket, Execution, Worker
from docket.dependencies import Cron
from docket.dependencies._cron import VIXIE_KEYWORDS

Expand Down Expand Up @@ -171,3 +175,59 @@ def test_standard_expression_not_modified():
"""Standard 5-field expressions pass through without modification."""
cron = Cron("30 2 15 * *", automatic=False)
assert cron.expression == "30 2 15 * *"


async def test_a_run_that_overlaps_its_next_slot_is_followed_by_that_slot(
docket: Docket, worker: Worker
):
"""Each run's schedule starts when the run starts, so a run still going at
its next slot is followed by that slot's run, not the one after it."""
whens: list[datetime] = []

async def overlapping(
cron: Cron = Cron("* * * * * *"),
execution: Execution = CurrentExecution(),
):
whens.append(execution.when)
await asyncio.sleep(1.5)

docket.register(overlapping)
await worker.run_at_most({"overlapping": 2})

assert whens[1] - whens[0] == timedelta(seconds=1)


# docket-rs's tests read the same table, so both implementations accept and
# refuse the same expressions, and find the same next match for each one.
CRON_TABLE = json.loads(
(Path(__file__).parents[3] / "conformance" / "cron-expressions.json").read_text()
)
Comment on lines +200 to +204

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the exhaustive parser cases out of fundamentals

The shared 53-expression acceptance/refusal table is exhaustive parser compatibility and error-condition coverage rather than a newcomer-facing happy path. Keeping these parametrizations in tests/fundamentals makes the living-documentation suite depend on a large external fixture and directly conflicts with its prescribed scope; move them to a regular cron test module while retaining the concise overlap example here.

AGENTS.md reference: python/tests/fundamentals/AGENTS.md:L144-L147

Useful? React with 👍 / 👎.



def _instant(text: str) -> datetime:
return datetime.fromisoformat(text.replace("Z", "+00:00"))


@pytest.mark.parametrize(
"expression, expected",
[
(row["expression"], row["next"])
for row in CRON_TABLE["expressions"]
if row["next"] is not None
],
)
def test_cron_finds_the_next_match_in_the_shared_table(expression: str, expected: str):
with patch("docket.dependencies._cron.datetime") as clock:
clock.now.return_value = _instant(CRON_TABLE["after"])
cron = Cron(expression, automatic=False)

assert cron.next_time() == _instant(expected)


@pytest.mark.parametrize(
"expression",
[row["expression"] for row in CRON_TABLE["expressions"] if row["next"] is None],
)
def test_cron_refuses_each_expression_the_shared_table_refuses(expression: str):
with pytest.raises(CronSimError):
Cron(expression, automatic=False)
41 changes: 35 additions & 6 deletions rust/docket/src/behaviors/cron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@ use crate::task::Task;
/// adds it when it starts, so its arguments need a `Default`.
/// [`Cron::manual`] runs it only after something adds it.
///
/// Expressions have five fields, or one of `@yearly`, `@annually`,
/// `@monthly`, `@weekly`, `@daily`, `@midnight`, and `@hourly`.
/// Expressions have five fields, or six with seconds first, or are one of
/// `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight`, and
/// `@hourly`. They mean what they mean in pydocket, which refuses a field
/// for the year, `?`, a `W` other than `LW`, and an expression that never
/// matches, so this does too.
///
/// Each run's next match counts from when the run started, so a run still
/// going at its next match is followed by that match's run at once.
#[derive(Clone, Debug)]
pub struct Cron<Mode = Automatic> {
schedule: croner::Cron,
Expand All @@ -37,6 +43,11 @@ impl Cron {
let schedule = croner::Cron::from_str(expression).map_err(|error| {
Error::Invalid(format!("{expression} is not a cron expression: {error}"))
})?;
if let Some(reason) = refused_by_pydocket(expression, &schedule) {
return Err(Error::Invalid(format!(
"{expression} is not a cron expression: {reason}"
)));
}
Ok(Self {
schedule,
timezone: Tz::UTC,
Expand All @@ -55,6 +66,25 @@ impl Cron {
}
}

/// Why pydocket's parser refuses an expression that croner accepts, if it
/// does. The day of the month is the third field from the end, both with
/// and without a field for the seconds.
fn refused_by_pydocket(expression: &str, schedule: &croner::Cron) -> Option<&'static str> {
let fields: Vec<&str> = expression.split_whitespace().collect();
let day_of_month = fields.len().checked_sub(3).map(|index| fields[index]);
if fields.len() == 7 {
Some("it has a field for the year")
} else if expression.contains('?') {
Some("it uses ?")
} else if day_of_month.is_some_and(|day| day.contains('W') && day != "LW") {
Some("its day of the month uses W, other than LW")
Comment on lines +79 to +80

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make the W rejection case-insensitive

For lowercase special syntax such as 0 0 15w * *, cronsim uppercases fields before parsing and rejects it just like 15W, while croner accepts lowercase cron syntax; this raw, case-sensitive check therefore lets the Rust expression through. Normalize the day-of-month field before checking W so the promised parser parity also covers casing variants.

Useful? React with 👍 / 👎.

} else if schedule.find_next_occurrence(&Utc::now(), false).is_err() {
Some("it never matches")
} else {
None
}
}

impl<Mode> Cron<Mode> {
/// Reads the schedule in `timezone`, so that it follows daylight saving
/// time there.
Expand Down Expand Up @@ -106,10 +136,9 @@ impl Completion for Schedule {
let control = ctx
.perpetual()
.expect("a cron task gives each run its control");
match self.cron.next_after(Utc::now()) {
Some(next) => control.decide(next),
None => AfterCompletion::Finish,
}
self.cron
.next_after(control.started_at)
.map_or(AfterCompletion::Finish, |next| control.decide(next))
}
}

Expand Down
Loading
Loading