-
Notifications
You must be signed in to change notification settings - Fork 6
Add Cron dependency for cron-style task scheduling #311
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| """Cron-style scheduling dependency.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime, timezone | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from croniter import croniter | ||
|
|
||
| from ._perpetual import Perpetual | ||
|
|
||
| if TYPE_CHECKING: # pragma: no cover | ||
| from ._base import TaskOutcome | ||
| from ..execution import Execution | ||
|
|
||
|
|
||
| class Cron(Perpetual): | ||
| """Declare a task that should run on a cron schedule. Cron tasks are automatically | ||
| rescheduled for the next matching time after they finish (whether they succeed or | ||
| fail). By default, a cron task is scheduled at worker startup with `automatic=True`. | ||
|
|
||
| Unlike `Perpetual` which schedules based on intervals from the current time, `Cron` | ||
| schedules based on wall-clock time, ensuring tasks run at consistent times regardless | ||
| of execution duration or delays. | ||
|
|
||
| Supports standard cron expressions and Vixie cron-style keywords (@daily, @hourly, etc.) | ||
| via the croniter library. | ||
|
|
||
| Example: | ||
|
|
||
| ```python | ||
| @task | ||
| async def weekly_report(cron: Cron = Cron("0 9 * * 1")) -> None: | ||
| # Runs every Monday at 9:00 AM UTC | ||
| ... | ||
|
|
||
| @task | ||
| async def daily_cleanup(cron: Cron = Cron("@daily")) -> None: | ||
| # Runs every day at midnight UTC | ||
| ... | ||
| ``` | ||
| """ | ||
|
|
||
| expression: str | ||
|
|
||
| _croniter: croniter[datetime] | ||
|
|
||
| def __init__( | ||
| self, | ||
| expression: str, | ||
| automatic: bool = True, | ||
| ) -> None: | ||
| """ | ||
| Args: | ||
| expression: A cron expression string. Supports: | ||
| - Standard 5-field syntax: "minute hour day month weekday" | ||
| (e.g., "0 9 * * 1" for Mondays at 9 AM) | ||
| - Vixie cron keywords: @yearly, @annually, @monthly, @weekly, | ||
| @daily, @midnight, @hourly | ||
| automatic: If set, this task will be automatically scheduled during worker | ||
| startup and continually through the worker's lifespan. This ensures | ||
| that the task will always be scheduled despite crashes and other | ||
| adverse conditions. Automatic tasks must not require any arguments. | ||
| """ | ||
| super().__init__(automatic=automatic) | ||
| self.expression = expression | ||
| self._croniter = croniter(expression, datetime.now(timezone.utc), datetime) | ||
|
|
||
| async def __aenter__(self) -> Cron: | ||
| execution = self.execution.get() | ||
| cron = Cron(expression=self.expression, automatic=self.automatic) | ||
| cron.args = execution.args | ||
| cron.kwargs = execution.kwargs | ||
| return cron | ||
|
|
||
| @property | ||
| def initial_when(self) -> datetime: | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤌 |
||
| """Return the next cron time for initial scheduling.""" | ||
| return self._croniter.get_next() | ||
|
|
||
| async def on_complete(self, execution: Execution, outcome: TaskOutcome) -> bool: | ||
| """Handle completion by scheduling the next execution at the exact cron time. | ||
|
|
||
| This overrides Perpetual's on_complete to ensure we hit the exact wall-clock | ||
| time rather than adjusting for task duration. | ||
| """ | ||
| self.at(self._croniter.get_next()) | ||
| return await super().on_complete(execution, outcome) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -61,11 +61,16 @@ def __init__( | |
|
|
||
| async def __aenter__(self) -> Perpetual: | ||
| execution = self.execution.get() | ||
| perpetual = Perpetual(every=self.every) | ||
| perpetual = Perpetual(every=self.every, automatic=self.automatic) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great catch! :doh: |
||
| perpetual.args = execution.args | ||
| perpetual.kwargs = execution.kwargs | ||
| return perpetual | ||
|
|
||
| @property | ||
| def initial_when(self) -> datetime | None: | ||
| """Return None to schedule for immediate execution at worker startup.""" | ||
| return None | ||
|
|
||
| def cancel(self) -> None: | ||
| self.cancelled = True | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| """Tests for Cron dependency (cron-style scheduled tasks).""" | ||
|
|
||
| from datetime import datetime, timedelta, timezone | ||
| from unittest.mock import patch | ||
|
|
||
| from croniter import croniter | ||
|
|
||
| from docket import Docket, Worker | ||
| from docket.dependencies import Cron | ||
|
|
||
|
|
||
| async def test_cron_task_reschedules_itself(docket: Docket, worker: Worker): | ||
| """Cron tasks automatically reschedule after each execution.""" | ||
| runs = 0 | ||
|
|
||
| async def my_cron_task(cron: Cron = Cron("0 9 * * *", automatic=False)): | ||
| nonlocal runs | ||
| runs += 1 | ||
|
|
||
| # Patch croniter.get_next to return a time 10ms in the future | ||
| with patch.object( | ||
| croniter, | ||
| "get_next", | ||
| return_value=datetime.now(timezone.utc) + timedelta(milliseconds=10), | ||
| ): | ||
| execution = await docket.add(my_cron_task)() | ||
| await worker.run_at_most({execution.key: 3}) | ||
|
|
||
| assert runs == 3 | ||
|
|
||
|
|
||
| async def test_cron_tasks_are_automatically_scheduled(docket: Docket, worker: Worker): | ||
| """Cron tasks with automatic=True are scheduled at worker startup.""" | ||
| calls = 0 | ||
|
|
||
| async def my_automatic_cron( | ||
| cron: Cron = Cron("0 0 * * *"), | ||
| ): # automatic=True is default | ||
| nonlocal calls | ||
| calls += 1 | ||
|
|
||
| docket.register(my_automatic_cron) | ||
|
|
||
| with patch.object( | ||
| croniter, | ||
| "get_next", | ||
| return_value=datetime.now(timezone.utc) + timedelta(milliseconds=10), | ||
| ): | ||
| await worker.run_at_most({"my_automatic_cron": 2}) | ||
|
|
||
| assert calls == 2 | ||
|
|
||
|
|
||
| async def test_cron_tasks_continue_after_errors(docket: Docket, worker: Worker): | ||
| """Cron tasks keep rescheduling even when they raise exceptions.""" | ||
| calls = 0 | ||
|
|
||
| async def flaky_cron_task(cron: Cron = Cron("0 * * * *", automatic=False)): | ||
| nonlocal calls | ||
| calls += 1 | ||
| raise ValueError("Task failed!") | ||
|
|
||
| with patch.object( | ||
| croniter, | ||
| "get_next", | ||
| return_value=datetime.now(timezone.utc) + timedelta(milliseconds=10), | ||
| ): | ||
| execution = await docket.add(flaky_cron_task)() | ||
| await worker.run_at_most({execution.key: 3}) | ||
|
|
||
| assert calls == 3 | ||
|
|
||
|
|
||
| async def test_cron_tasks_can_cancel_themselves(docket: Docket, worker: Worker): | ||
| """A cron task can stop rescheduling by calling cron.cancel().""" | ||
| calls = 0 | ||
|
|
||
| async def limited_cron_task(cron: Cron = Cron("0 * * * *", automatic=False)): | ||
| nonlocal calls | ||
| calls += 1 | ||
| if calls >= 3: | ||
| cron.cancel() | ||
|
|
||
| with patch.object( | ||
| croniter, | ||
| "get_next", | ||
| return_value=datetime.now(timezone.utc) + timedelta(milliseconds=10), | ||
| ): | ||
| await docket.add(limited_cron_task)() | ||
| await worker.run_until_finished() | ||
|
|
||
| assert calls == 3 | ||
|
|
||
|
|
||
| async def test_cron_supports_vixie_keywords(docket: Docket, worker: Worker): | ||
| """Cron supports Vixie cron keywords like @daily, @weekly, @hourly.""" | ||
| runs = 0 | ||
|
|
||
| # @daily is equivalent to "0 0 * * *" (midnight every day) | ||
| async def daily_task(cron: Cron = Cron("@daily", automatic=False)): | ||
| nonlocal runs | ||
| runs += 1 | ||
|
|
||
| with patch.object( | ||
| croniter, | ||
| "get_next", | ||
| return_value=datetime.now(timezone.utc) + timedelta(milliseconds=10), | ||
| ): | ||
| execution = await docket.add(daily_task)() | ||
| await worker.run_at_most({execution.key: 1}) | ||
|
|
||
| assert runs == 1 | ||
|
|
||
|
|
||
| async def test_automatic_cron_waits_for_scheduled_time(docket: Docket, worker: Worker): | ||
| """Automatic cron tasks wait for their next scheduled time instead of running immediately. | ||
|
|
||
| Unlike Perpetual tasks which run immediately at worker startup, Cron tasks | ||
| schedule themselves for the next matching cron time. This ensures a Monday 9 AM | ||
| cron doesn't accidentally run on a Wednesday startup. | ||
| """ | ||
| calls: list[datetime] = [] | ||
|
|
||
| async def scheduled_task(cron: Cron = Cron("0 9 * * 1")): # Mondays at 9 AM | ||
| calls.append(datetime.now(timezone.utc)) | ||
|
|
||
| docket.register(scheduled_task) | ||
|
|
||
| # Schedule for 100ms in the future (simulating next Monday 9 AM) | ||
| future_time = datetime.now(timezone.utc) + timedelta(milliseconds=100) | ||
| with patch.object(croniter, "get_next", return_value=future_time): | ||
| await worker.run_at_most({"scheduled_task": 1}) | ||
|
|
||
| assert len(calls) == 1 | ||
| # The task ran at or after the scheduled time, not immediately | ||
| assert calls[0] >= future_time - timedelta(milliseconds=50) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for pointing me to the new pallets repo, it's unfortunate that the pypi page still has that huge warning on it. I'm good with this!
@zzstoatzz I don't know if you realized this, but
croniterlives! https://github.com/pallets-eco/croniter They just haven't removed the goofy warning on PyPI, but there's a bug report about it.Maybe time to go back in Prefect?