Skip to content

Commit 6a6907f

Browse files
committed
Fix memory leak in the timer
We were creating two futures, but only awaiting until the one of them finished and not canceling the second. Because `reset()` was never called, we were just creating more and more futures that would never complete. This change fixes this by canceling the second task immediately after the first one is complete. Signed-off-by: Sahas Subramanian <[email protected]>
1 parent 5ab1279 commit 6a6907f

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/frequenz/channels/timer.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -682,14 +682,20 @@ async def ready(self) -> bool: # noqa: DOC502
682682
# could be reset while we are sleeping, in which case we need to recalculate
683683
# the time to the next tick and try again.
684684
while time_to_next_tick > 0:
685-
await next(
686-
asyncio.as_completed(
687-
[
688-
asyncio.sleep(time_to_next_tick / 1_000_000),
689-
self._reset_event.wait(),
690-
]
691-
)
685+
_, pending = await asyncio.wait(
686+
[
687+
asyncio.create_task(asyncio.sleep(time_to_next_tick / 1_000_000)),
688+
asyncio.create_task(self._reset_event.wait()),
689+
],
690+
return_when=asyncio.FIRST_COMPLETED,
692691
)
692+
for task in pending:
693+
task.cancel()
694+
try:
695+
await task
696+
except asyncio.CancelledError:
697+
pass
698+
693699
self._reset_event.clear()
694700
now = self._now()
695701
time_to_next_tick = self._next_tick_time - now

0 commit comments

Comments
 (0)