Skip to content

Commit

Permalink
feat: add new CronTrigger task type (#1632)
Browse files Browse the repository at this point in the history
* [feat] Add CronTrigger

* [feat] Add timezone support to CronTrigger

* docs: utc -> tz rename

Signed-off-by: 18 <[email protected]>

* ci: correct from checks.

* docs: specify tz as datetime attribute

I'm aware that datetime is not what it actually is, but we shouldn't be using private data types in our docstrings. Developers will additionally be using it as a reference, not the literal representation when using

Signed-off-by: 18 <[email protected]>

---------

Signed-off-by: 18 <[email protected]>
Co-authored-by: 18 <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Mar 30, 2024
1 parent ced71df commit a6ec7f3
Show file tree
Hide file tree
Showing 3 changed files with 2,532 additions and 25 deletions.
22 changes: 21 additions & 1 deletion interactions/models/internal/tasks/triggers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from abc import ABC, abstractmethod
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta, timezone, _TzInfo

from croniter import croniter

__all__ = ("BaseTrigger", "IntervalTrigger", "DateTrigger", "TimeTrigger", "OrTrigger")

Expand Down Expand Up @@ -140,3 +142,21 @@ def _set_current_trigger(self) -> BaseTrigger | None:

def next_fire(self) -> datetime | None:
return self.current_trigger.next_fire() if self._set_current_trigger() else None


class CronTrigger(BaseTrigger):
"""
Trigger the task based on a cron schedule.
Attributes:
cron str: The cron schedule, use https://crontab.guru for help
tz datetime: Whether or not to use UTC for the time (uses timezone information)
"""

def __init__(self, cron: str, tz: _TzInfo = timezone.utc) -> None:
self.cron = cron
self.tz = tz

def next_fire(self) -> datetime | None:
return croniter(self.cron, datetime.now(tz=self.tz)).next(datetime)
Loading

0 comments on commit a6ec7f3

Please sign in to comment.