|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | | -from asyncio import Task, create_task, gather, sleep |
| 5 | +from asyncio import CancelledError, Task, create_task, gather, sleep |
6 | 6 | from collections.abc import Awaitable, Callable |
7 | 7 | from dataclasses import replace |
8 | 8 | from datetime import UTC, datetime, timedelta |
@@ -854,11 +854,14 @@ async def _relay_update_lock( |
854 | 854 | ) |
855 | 855 | await self.save_cache() |
856 | 856 |
|
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) |
862 | 865 |
|
863 | 866 | async def clock_synchronize(self) -> bool: |
864 | 867 | """Synchronize clock. Returns true if successful.""" |
@@ -1094,12 +1097,10 @@ async def unload(self) -> None: |
1094 | 1097 | if self._cache_enabled: |
1095 | 1098 | await self._energy_log_records_save_to_cache() |
1096 | 1099 |
|
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: |
1102 | 1101 | self._clock_synchronize_task.cancel() |
| 1102 | + await gather(self._clock_synchronize_task, return_exceptions=True) |
| 1103 | + self._clock_synchronize_task = None |
1103 | 1104 |
|
1104 | 1105 | await super().unload() |
1105 | 1106 |
|
|
0 commit comments