Skip to content

Keep a reference to asyncio tasks #1982

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
merged 1 commit into from
Aug 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions can/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ def __init__(
self._lock = threading.Lock()

self._readers: list[Union[int, threading.Thread]] = []
self._tasks: set[asyncio.Task] = set()
_bus_list: list[BusABC] = bus if isinstance(bus, list) else [bus]
for each_bus in _bus_list:
self.add_bus(each_bus)
Expand Down Expand Up @@ -256,8 +257,10 @@ def _on_message_received(self, msg: Message) -> None:
for callback in self.listeners:
res = callback(msg)
if res and self._loop and asyncio.iscoroutine(res):
# Schedule coroutine
self._loop.create_task(res)
# Schedule coroutine and keep a reference to the task
task = self._loop.create_task(res)
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)

def _on_error(self, exc: Exception) -> bool:
"""Calls ``on_error()`` for all listeners if they implement it.
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/1938.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Keep a reference to asyncio tasks in `can.Notifier` as recommended by [python documentation](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task).
Loading