Skip to content

Commit e527f81

Browse files
committed
CR: Drain cancellation to avoid “Task exception was never retrieved”.
CR: Make the scheduler resilient: fix return type, handle cancellation, and keep the loop alive on errors. CR: Import CancelledError for proper task shutdown handling.
1 parent 1446502 commit e527f81

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

plugwise_usb/nodes/circle.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from __future__ import annotations
44

5-
from asyncio import Task, create_task, gather, sleep
5+
from asyncio import CancelledError, Task, create_task, gather, sleep
66
from collections.abc import Awaitable, Callable
77
from dataclasses import replace
88
from datetime import UTC, datetime, timedelta
@@ -854,11 +854,14 @@ async def _relay_update_lock(
854854
)
855855
await self.save_cache()
856856

857-
async def _clock_synchronize_scheduler(self) -> bool:
858-
"""Synchronize clock scheduler."""
859-
while True:
860-
await sleep(60)
861-
await self.clock_synchronize()
857+
async def _clock_synchronize_scheduler(self) -> None:
858+
"""Background task: periodically synchronize the clock until cancelled."""
859+
try:
860+
while True:
861+
await sleep(60)
862+
await self.clock_synchronize()
863+
except CancelledError:
864+
_LOGGER.debug("Clock sync scheduler cancelled for %s", self.name)
862865

863866
async def clock_synchronize(self) -> bool:
864867
"""Synchronize clock. Returns true if successful."""
@@ -1094,12 +1097,10 @@ async def unload(self) -> None:
10941097
if self._cache_enabled:
10951098
await self._energy_log_records_save_to_cache()
10961099

1097-
if (
1098-
hasattr(self, "_clock_synchronize_task")
1099-
and self._clock_synchronize_task
1100-
and not self._clock_synchronize_task.done()
1101-
):
1100+
if self._clock_synchronize_task:
11021101
self._clock_synchronize_task.cancel()
1102+
await gather(self._clock_synchronize_task, return_exceptions=True)
1103+
self._clock_synchronize_task = None
11031104

11041105
await super().unload()
11051106

0 commit comments

Comments
 (0)