Simplify async_track_time_interval implementation (#117956)

This commit is contained in:
J. Nick Koston 2024-05-22 21:56:49 -10:00 committed by GitHub
parent fc4ea774ca
commit 6c6a5f496a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1571,11 +1571,10 @@ class _TrackTimeInterval:
cancel_on_shutdown: bool | None
_track_job: HassJob[[datetime], Coroutine[Any, Any, None] | None] | None = None
_run_job: HassJob[[datetime], Coroutine[Any, Any, None] | None] | None = None
_cancel_callback: CALLBACK_TYPE | None = None
_timer_handle: asyncio.TimerHandle | None = None
def async_attach(self) -> None:
"""Initialize track job."""
hass = self.hass
self._track_job = HassJob(
self._interval_listener,
self.job_name,
@ -1587,32 +1586,32 @@ class _TrackTimeInterval:
f"track time interval {self.seconds}",
cancel_on_shutdown=self.cancel_on_shutdown,
)
self._cancel_callback = async_call_at(
hass,
self._track_job,
hass.loop.time() + self.seconds,
self._schedule_timer()
def _schedule_timer(self) -> None:
"""Schedule the timer."""
if TYPE_CHECKING:
assert self._track_job is not None
hass = self.hass
loop = hass.loop
self._timer_handle = loop.call_at(
loop.time() + self.seconds, self._interval_listener, self._track_job
)
@callback
def _interval_listener(self, now: datetime) -> None:
def _interval_listener(self, _: Any) -> None:
"""Handle elapsed intervals."""
if TYPE_CHECKING:
assert self._run_job is not None
assert self._track_job is not None
hass = self.hass
self._cancel_callback = async_call_at(
hass,
self._track_job,
hass.loop.time() + self.seconds,
)
hass.async_run_hass_job(self._run_job, now, background=True)
self._schedule_timer()
self.hass.async_run_hass_job(self._run_job, dt_util.utcnow(), background=True)
@callback
def async_cancel(self) -> None:
"""Cancel the call_at."""
if TYPE_CHECKING:
assert self._cancel_callback is not None
self._cancel_callback()
assert self._timer_handle is not None
self._timer_handle.cancel()
@callback