diff --git a/src/viam/sessions_client.py b/src/viam/sessions_client.py index 7ceef8740..b8ab6c2d1 100644 --- a/src/viam/sessions_client.py +++ b/src/viam/sessions_client.py @@ -35,12 +35,6 @@ def loop_kwargs(): return {"loop": asyncio.get_running_loop()} return {} - -async def delay(coro, seconds): - await asyncio.sleep(seconds, **loop_kwargs()) - await coro - - class SessionsClient: """ A Session allows a client to express that it is actively connected and @@ -116,10 +110,22 @@ async def metadata(self) -> _MetadataLike: self._heartbeat_interval = response.heartbeat_window.ToTimedelta() self._current_id = response.id + # tick once to ensure heartbeats are supported await self._heartbeat_tick() + if self._supported: + # We send heartbeats slightly faster than the interval window to + # ensure that we don't fall outside of it and expire the session. + wait = self._heartbeat_interval.total_seconds() / 5 + asyncio.create_task(self._heartbeat_task(wait), name=f"{_TASK_PREFIX}-heartbeat") + return self._metadata + async def _heartbeat_task(self, wait: float): + while self._supported: + await asyncio.sleep(wait) + await self._heartbeat_tick() + async def _heartbeat_tick(self): if not self._supported: return @@ -139,10 +145,6 @@ async def _heartbeat_tick(self): self.reset() else: LOGGER.debug("Sent heartbeat successfully") - # We send heartbeats slightly faster than the interval window to - # ensure that we don't fall outside of it and expire the session. - wait = self._heartbeat_interval.total_seconds() / 5 - asyncio.create_task(delay(self._heartbeat_tick(), wait), name=f"{_TASK_PREFIX}-heartbeat") @property def _metadata(self) -> _MetadataLike: