|
| 1 | +"""Cron-style scheduling dependency.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from datetime import datetime, timezone |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +from croniter import croniter |
| 9 | + |
| 10 | +from ._perpetual import Perpetual |
| 11 | + |
| 12 | +if TYPE_CHECKING: # pragma: no cover |
| 13 | + from ._base import TaskOutcome |
| 14 | + from ..execution import Execution |
| 15 | + |
| 16 | + |
| 17 | +class Cron(Perpetual): |
| 18 | + """Declare a task that should run on a cron schedule. Cron tasks are automatically |
| 19 | + rescheduled for the next matching time after they finish (whether they succeed or |
| 20 | + fail). By default, a cron task is scheduled at worker startup with `automatic=True`. |
| 21 | +
|
| 22 | + Unlike `Perpetual` which schedules based on intervals from the current time, `Cron` |
| 23 | + schedules based on wall-clock time, ensuring tasks run at consistent times regardless |
| 24 | + of execution duration or delays. |
| 25 | +
|
| 26 | + Supports standard cron expressions and Vixie cron-style keywords (@daily, @hourly, etc.) |
| 27 | + via the croniter library. |
| 28 | +
|
| 29 | + Example: |
| 30 | +
|
| 31 | + ```python |
| 32 | + @task |
| 33 | + async def weekly_report(cron: Cron = Cron("0 9 * * 1")) -> None: |
| 34 | + # Runs every Monday at 9:00 AM UTC |
| 35 | + ... |
| 36 | +
|
| 37 | + @task |
| 38 | + async def daily_cleanup(cron: Cron = Cron("@daily")) -> None: |
| 39 | + # Runs every day at midnight UTC |
| 40 | + ... |
| 41 | + ``` |
| 42 | + """ |
| 43 | + |
| 44 | + expression: str |
| 45 | + |
| 46 | + _croniter: croniter[datetime] |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + expression: str, |
| 51 | + automatic: bool = True, |
| 52 | + ) -> None: |
| 53 | + """ |
| 54 | + Args: |
| 55 | + expression: A cron expression string. Supports: |
| 56 | + - Standard 5-field syntax: "minute hour day month weekday" |
| 57 | + (e.g., "0 9 * * 1" for Mondays at 9 AM) |
| 58 | + - Vixie cron keywords: @yearly, @annually, @monthly, @weekly, |
| 59 | + @daily, @midnight, @hourly |
| 60 | + automatic: If set, this task will be automatically scheduled during worker |
| 61 | + startup and continually through the worker's lifespan. This ensures |
| 62 | + that the task will always be scheduled despite crashes and other |
| 63 | + adverse conditions. Automatic tasks must not require any arguments. |
| 64 | + """ |
| 65 | + super().__init__(automatic=automatic) |
| 66 | + self.expression = expression |
| 67 | + self._croniter = croniter(expression, datetime.now(timezone.utc), datetime) |
| 68 | + |
| 69 | + async def __aenter__(self) -> Cron: |
| 70 | + execution = self.execution.get() |
| 71 | + cron = Cron(expression=self.expression, automatic=self.automatic) |
| 72 | + cron.args = execution.args |
| 73 | + cron.kwargs = execution.kwargs |
| 74 | + return cron |
| 75 | + |
| 76 | + def get_next(self) -> datetime: |
| 77 | + return self._croniter.get_next() |
| 78 | + |
| 79 | + async def on_complete(self, execution: Execution, outcome: TaskOutcome) -> bool: |
| 80 | + """Handle completion by scheduling the next execution at the exact cron time. |
| 81 | +
|
| 82 | + This overrides Perpetual's on_complete to ensure we hit the exact wall-clock |
| 83 | + time rather than adjusting for task duration. |
| 84 | + """ |
| 85 | + self.at(self.get_next()) |
| 86 | + return await super().on_complete(execution, outcome) |
0 commit comments