Skip to content

Commit 7721047

Browse files
committed
stop cleanup task when manager is destroyed
1 parent 3b8d6db commit 7721047

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

botcore/utils/cooldown.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import random
77
import time
88
import typing
9+
import weakref
910
from collections.abc import Awaitable, Hashable, Iterable
1011
from contextlib import suppress
1112
from dataclasses import dataclass
@@ -105,6 +106,7 @@ def __init__(self, *, cooldown_duration: float):
105106
self._periodical_cleanup(random.uniform(0, 10)),
106107
name="CooldownManager cleanup",
107108
)
109+
weakref.finalize(self, self.cleanup_task.cancel)
108110

109111
def set_cooldown(self, channel: Hashable, call_arguments: Iterable[object]) -> None:
110112
"""Set `call_arguments` arguments on cooldown in `channel`."""
@@ -144,11 +146,15 @@ async def _periodical_cleanup(self, initial_delay: float) -> None:
144146
Delete stale items every hour after waiting for `initial_delay`.
145147
146148
The `initial_delay` ensures cleanups are not running for every command at the same time.
149+
A strong reference to self is only kept while cleanup is running.
147150
"""
151+
weak_self = weakref.ref(self)
152+
del self
153+
148154
await asyncio.sleep(initial_delay)
149155
while True:
150156
await asyncio.sleep(60 * 60)
151-
self._delete_stale_items()
157+
weak_self()._delete_stale_items()
152158

153159
def _delete_stale_items(self) -> None:
154160
"""Remove expired items from internal collections."""

0 commit comments

Comments
 (0)