diff --git a/can/notifier.py b/can/notifier.py index b2f550df7..a2ee512fc 100644 --- a/can/notifier.py +++ b/can/notifier.py @@ -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) @@ -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. diff --git a/doc/changelog.d/1938.fixed.md b/doc/changelog.d/1938.fixed.md new file mode 100644 index 000000000..f9aad1089 --- /dev/null +++ b/doc/changelog.d/1938.fixed.md @@ -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).