Skip to content

Commit 7f60548

Browse files
authored
Implement ServiceBase using a new PersistentTaskGroup (#30)
`asyncio.TaskGroup` is a very convenient construct when using parallelization for doing calculations for example, where the results for all the tasks need to be merged together to produce a final result. In this case if one of the tasks fails, it makes sense to cancel the others and abort as soon as possible, as any further calculations would be thrown away. This PR introduces a new `PersistentTaskGroup` class, intended to help managing a group of tasks that should persist even if other tasks in the group fail, usually by either only discarding the failed task or by restarting it somehow. The `ServiceBase` class is updated to use a `PersistentTaskGroup` underneath, and it is simplified for single-task services by making the service driven by a single `main` task, which can use the new group to monitor sub-tasks and act accordingly. This is part of #27 and #9.
2 parents 79776f0 + bd468e7 commit 7f60548

File tree

7 files changed

+1026
-200
lines changed

7 files changed

+1026
-200
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# License: MIT
2+
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3+
4+
"""General purpose async tools.
5+
6+
This module provides general purpose async tools that can be used to simplify the
7+
development of asyncio-based applications.
8+
9+
The module provides the following classes and functions:
10+
11+
- [cancel_and_await][frequenz.core.asyncio.cancel_and_await]: A function that cancels a
12+
task and waits for it to finish, handling `CancelledError` exceptions.
13+
- [PersistentTaskGroup][frequenz.core.asyncio.PersistentTaskGroup]: An alternative to
14+
[`asyncio.TaskGroup`][] to manage tasks that run until explicitly stopped.
15+
- [Service][frequenz.core.asyncio.Service]: An interface for services running in the
16+
background.
17+
- [ServiceBase][frequenz.core.asyncio.ServiceBase]: A base class for implementing
18+
services running in the background.
19+
- [TaskCreator][frequenz.core.asyncio.TaskCreator]: A protocol for creating tasks.
20+
"""
21+
22+
from ._service import Service, ServiceBase
23+
from ._task_group import PersistentTaskGroup
24+
from ._util import TaskCreator, TaskReturnT, cancel_and_await
25+
26+
__all__ = [
27+
"PersistentTaskGroup",
28+
"Service",
29+
"ServiceBase",
30+
"TaskCreator",
31+
"TaskReturnT",
32+
"cancel_and_await",
33+
]

0 commit comments

Comments
 (0)