Skip to content

Commit

Permalink
Simplify Tasks (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
orsinium authored Feb 12, 2023
1 parent 0c4d3b4 commit 7f77cb0
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 15 deletions.
5 changes: 2 additions & 3 deletions tests/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ async def test_wait():
t = Tasks('tasks')
for _ in range(20):
t.start(asyncio.sleep(.001), 'task')
len(t._tasks) == 20
await t.wait()
assert len(t._tasks) == 20
for task in t._tasks:
assert task.done()
assert len(t._tasks) == 0


async def test_cancel():
Expand Down
2 changes: 1 addition & 1 deletion walnats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from ._services import Services


__version__ = '1.2.5'
__version__ = '1.2.6'
__all__ = [
# classes
'Actor',
Expand Down
16 changes: 5 additions & 11 deletions walnats/_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,23 @@
class Tasks:
"""Supervise multiple async tasks.
"""
__slots__ = ('_tasks', '_cleanup_every', '_since_cleanup', '_name', '_done')
__slots__ = ('_tasks', '_name', '_done')
_name: str
_tasks: list[asyncio.Task]
_cleanup_every: int
_since_cleanup: int
_tasks: set[asyncio.Task]
_done: bool

def __init__(self, name: str) -> None:
self._name = name
self._tasks = []
self._cleanup_every = 100
self._since_cleanup = 0
self._tasks = set()
self._done = False

def start(self, coro: Coroutine[None, None, None], name: str) -> None:
"""Create a new task and track it in the supervisor.
"""
assert not self._done
self._since_cleanup = (self._since_cleanup + 1) % self._cleanup_every
if self._since_cleanup == 0:
self._tasks = [t for t in self._tasks if not t.done()]
task = asyncio.create_task(coro, name=name)
self._tasks.append(task)
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)

def cancel(self) -> None:
"""Cancel all supervised tasks.
Expand Down

0 comments on commit 7f77cb0

Please sign in to comment.