-
Notifications
You must be signed in to change notification settings - Fork 30
Add scheduled tasks feature and delayed entity signals #160
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
berndverst
merged 11 commits into
microsoft:main
from
andystaples:andystaples/add-scheduled-tasks
Jun 29, 2026
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f8487e0
Add scheduled tasks feature and delayed entity signals
andystaples 8298f71
Merge remote-tracking branch 'origin/main' into andystaples/add-sched…
andystaples 58ee9c9
Let to_json hook take precedence over dataclass asdict in serializer
andystaples 4df10bc
Use to_json/from_json hooks for schedule options
andystaples 2dbff23
Serialization improvements (WIP)
andystaples 7ea7478
Revert JSON stuff to base
andystaples ab871db
Merge branch 'main' into andystaples/add-scheduled-tasks
andystaples 10657aa
Revert serialization test
andystaples e8186e7
Update scheduled tasks with new serialization fixes
andystaples cd53b73
PR Feedback
andystaples 9c84751
Address PR feedback: capability flag, datetime filter fix, helper con…
andystaples 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
Some comments aren't visible on the classic Files Changed page.
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
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,38 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
| """Scheduled tasks support for the Durable Task SDK. | ||
|
|
||
| This package provides a recurring schedule feature built on top of durable | ||
| entities and a helper orchestrator. Register the entity and orchestrator with a | ||
| worker via :func:`configure_scheduled_tasks`, then manage schedules from the | ||
| client via :class:`ScheduledTaskClient`. | ||
| """ | ||
|
|
||
| from durabletask.scheduled.client import ScheduleClient, ScheduledTaskClient | ||
| from durabletask.scheduled.exceptions import (ScheduleClientValidationError, | ||
| ScheduleError, | ||
| ScheduleInvalidTransitionError, | ||
| ScheduleNotFoundError) | ||
| from durabletask.scheduled.models import (ScheduleCreationOptions, | ||
| ScheduleDescription, ScheduleQuery, | ||
| ScheduleUpdateOptions) | ||
| from durabletask.scheduled.registration import configure_scheduled_tasks | ||
| from durabletask.scheduled.schedule_status import ScheduleStatus | ||
|
|
||
| __all__ = [ | ||
| "ScheduledTaskClient", | ||
| "ScheduleClient", | ||
| "ScheduleCreationOptions", | ||
| "ScheduleUpdateOptions", | ||
| "ScheduleDescription", | ||
| "ScheduleQuery", | ||
| "ScheduleStatus", | ||
| "ScheduleError", | ||
| "ScheduleNotFoundError", | ||
| "ScheduleClientValidationError", | ||
| "ScheduleInvalidTransitionError", | ||
| "configure_scheduled_tasks", | ||
| ] | ||
|
|
||
| PACKAGE_NAME = "durabletask.scheduled" |
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,154 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
| import logging | ||
|
|
||
| from durabletask.client import (EntityQuery, OrchestrationStatus, | ||
| TaskHubGrpcClient) | ||
| from durabletask.entities import EntityInstanceId | ||
| from durabletask.internal.helpers import ensure_aware | ||
| from durabletask.scheduled import transitions | ||
| from durabletask.scheduled.exceptions import ScheduleNotFoundError | ||
| from durabletask.scheduled.models import (ScheduleCreationOptions, | ||
| ScheduleDescription, ScheduleQuery, | ||
| ScheduleState, ScheduleUpdateOptions) | ||
| from durabletask.scheduled.orchestrator import ( | ||
| ScheduleOperationRequest, execute_schedule_operation_orchestrator) | ||
| from durabletask.scheduled.schedule_entity import (DELETE_OPERATION, | ||
| ENTITY_NAME) | ||
|
|
||
| logger = logging.getLogger("durabletask.scheduled") | ||
|
|
||
|
|
||
| class ScheduleClient: | ||
| """Client for managing a single schedule instance.""" | ||
|
|
||
| def __init__(self, client: TaskHubGrpcClient, schedule_id: str, | ||
| *, operation_timeout: float = 60): | ||
| if not schedule_id: | ||
| raise ValueError("schedule_id cannot be empty.") | ||
| self._client = client | ||
| self._schedule_id = schedule_id | ||
| self._entity_id = EntityInstanceId(ENTITY_NAME, schedule_id) | ||
| self._operation_timeout = operation_timeout | ||
|
|
||
| @property | ||
| def schedule_id(self) -> str: | ||
| """Gets the ID of this schedule.""" | ||
| return self._schedule_id | ||
|
|
||
| def _run_operation(self, operation_name: str, input: object | None = None) -> None: | ||
| request = ScheduleOperationRequest( | ||
| entity_id=str(self._entity_id), | ||
| operation_name=operation_name, | ||
| input=input, | ||
| ) | ||
| instance_id = self._client.schedule_new_orchestration( | ||
| execute_schedule_operation_orchestrator, input=request) | ||
| state = self._client.wait_for_orchestration_completion( | ||
| instance_id, timeout=self._operation_timeout) | ||
| if state is None or state.runtime_status != OrchestrationStatus.COMPLETED: | ||
| failure = state.failure_details if state else None | ||
| message = failure.message if failure else "unknown error" | ||
| raise RuntimeError( | ||
| f"Failed to '{operation_name}' schedule '{self._schedule_id}': {message}") | ||
|
|
||
| def create(self, options: ScheduleCreationOptions) -> None: | ||
| """Create or update this schedule with the given configuration.""" | ||
| self._run_operation(transitions.CREATE_SCHEDULE, options) | ||
|
|
||
| def update(self, options: ScheduleUpdateOptions) -> None: | ||
| """Update this schedule's configuration.""" | ||
| self._run_operation(transitions.UPDATE_SCHEDULE, options) | ||
|
|
||
| def pause(self) -> None: | ||
| """Pause this schedule.""" | ||
| self._run_operation(transitions.PAUSE_SCHEDULE) | ||
|
|
||
| def resume(self) -> None: | ||
| """Resume this schedule.""" | ||
| self._run_operation(transitions.RESUME_SCHEDULE) | ||
|
|
||
| def delete(self) -> None: | ||
| """Delete this schedule.""" | ||
| self._run_operation(DELETE_OPERATION) | ||
|
|
||
| def describe(self) -> ScheduleDescription: | ||
| """Retrieve the current details of this schedule.""" | ||
| metadata = self._client.get_entity(self._entity_id, include_state=True) | ||
| if metadata is None: | ||
| raise ScheduleNotFoundError(self._schedule_id) | ||
| state = metadata.get_typed_state(ScheduleState) | ||
| if state is None: | ||
| raise ScheduleNotFoundError(self._schedule_id) | ||
| return state.to_description() | ||
|
|
||
|
|
||
| class ScheduledTaskClient: | ||
| """Client for managing scheduled tasks in a Durable Task application.""" | ||
|
|
||
| def __init__(self, client: TaskHubGrpcClient, *, operation_timeout: float = 60): | ||
| self._client = client | ||
| self._operation_timeout = operation_timeout | ||
|
|
||
| def get_schedule_client(self, schedule_id: str) -> ScheduleClient: | ||
| """Get a handle to manage a specific schedule.""" | ||
| return ScheduleClient(self._client, schedule_id, | ||
| operation_timeout=self._operation_timeout) | ||
|
|
||
| def create_schedule(self, options: ScheduleCreationOptions) -> ScheduleClient: | ||
| """Create a new schedule and return a client for managing it.""" | ||
| schedule_client = self.get_schedule_client(options.schedule_id) | ||
| schedule_client.create(options) | ||
| return schedule_client | ||
|
|
||
| def get_schedule(self, schedule_id: str) -> ScheduleDescription | None: | ||
| """Get a schedule description by ID, or None if it does not exist.""" | ||
| try: | ||
| return self.get_schedule_client(schedule_id).describe() | ||
| except ScheduleNotFoundError: | ||
| return None | ||
|
|
||
| def list_schedules(self, schedule_query: ScheduleQuery | None = None) -> list[ScheduleDescription]: | ||
| """List schedules matching the given filter criteria. | ||
|
|
||
| > [!NOTE] | ||
| > The ``status`` and ``created_from``/``created_to`` filters are applied | ||
| > client-side after each page of entities is fetched, so an individual | ||
| > page may contain fewer than ``page_size`` matches (or none) even when | ||
| > more matching schedules exist. This mirrors the .NET implementation. | ||
| """ | ||
| prefix = schedule_query.schedule_id_prefix if schedule_query and schedule_query.schedule_id_prefix else "" | ||
| page_size = (schedule_query.page_size if schedule_query and schedule_query.page_size | ||
| else ScheduleQuery.DEFAULT_PAGE_SIZE) | ||
| query = EntityQuery( | ||
| instance_id_starts_with=f"@{ENTITY_NAME}@{prefix}", | ||
| include_state=True, | ||
| page_size=page_size, | ||
| ) | ||
| results: list[ScheduleDescription] = [] | ||
| for metadata in self._client.get_all_entities(query): | ||
|
andystaples marked this conversation as resolved.
|
||
| state = metadata.get_typed_state(ScheduleState) | ||
| if state is None or state.schedule_configuration is None: | ||
| continue | ||
| if not self._matches_filter(state, schedule_query): | ||
| continue | ||
| results.append(state.to_description()) | ||
| return results | ||
|
|
||
| @staticmethod | ||
| def _matches_filter(state: ScheduleState, schedule_query: ScheduleQuery | None) -> bool: | ||
| if schedule_query is None: | ||
| return True | ||
| if schedule_query.status is not None and state.status != schedule_query.status: | ||
| return False | ||
| # ``ScheduleQuery`` normalizes its bounds to aware UTC; defensively | ||
| # normalize the stored timestamp too (a payload could in principle carry | ||
| # a naive value) so the comparison can never raise on naive-vs-aware. | ||
| # Bounds are exclusive, matching the .NET ScheduledTasks implementation. | ||
| created_at = ensure_aware(state.schedule_created_at) | ||
| if schedule_query.created_from is not None and not (created_at and created_at > schedule_query.created_from): | ||
| return False | ||
| if schedule_query.created_to is not None and not (created_at and created_at < schedule_query.created_to): | ||
| return False | ||
|
andystaples marked this conversation as resolved.
|
||
| return True | ||
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.
Uh oh!
There was an error while loading. Please reload this page.