remotivelabs.topology.time.async_ticker

 1from __future__ import annotations
 2
 3import asyncio
 4import logging
 5import time
 6
 7from remotivelabs.topology.time.callback import OnTickCallback
 8
 9_logger = logging.getLogger(__name__)
10
11
12async def _ticker(interval_in_sec: float, on_tick: OnTickCallback):
13    """
14    Runs an infinite loop that calls the on_tick callback at the given interval. It takes into account the time it takes to execute the
15    callback and adjusts the sleep time accordingly.
16
17    Note: if sleep time is negative, we're behind schedule. We use the special sleep(0), which avoids being scheduled on the event loop and
18    only yields if there are other tasks waiting to run. This is the fastest way to "catch up", but it is still "best effort".
19
20    It is possible to stop the ticker by returning True from the on_tick callback. You can also stop the ticker by cancelling the task.
21    """
22    _logger.debug(f"timer scheduled at every {interval_in_sec} seconds")
23    start_time = time.monotonic()
24    last_tick = start_time
25    total_drift = 0.0
26
27    try:
28        # initial delay
29        await asyncio.sleep(interval_in_sec)
30
31        # loop until cancelled or callback returns False
32        while True:
33            tick_time = time.monotonic()
34            elapsed_time = tick_time - start_time  # total time since ticker start
35            since_last_tick = tick_time - last_tick  # time since last tick
36            total_drift += since_last_tick - interval_in_sec  # drift is the difference between the expected and actual time
37            last_tick = tick_time
38
39            if await on_tick(
40                elapsed_time=elapsed_time,
41                since_last_tick=since_last_tick,
42                total_drift=total_drift,
43                interval=interval_in_sec,
44            ):
45                break  # cancel the timer if the callback returns True
46
47            callback_duration = time.monotonic() - tick_time  # time it took to execute the callback
48
49            sleep_time = max(0, interval_in_sec - callback_duration)
50            await asyncio.sleep(sleep_time)
51
52    except asyncio.CancelledError:
53        _logger.debug("timer cancelled")
54
55
56def create_ticker(interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop | None = None) -> asyncio.Task:
57    """
58    Creates a ticker that calls the on_tick function at the given interval.
59
60    Note that the timer is a best effort timer. The actual interval may be longer than the specified interval if concurrent tasks are
61    unwilling to yield the CPU.
62
63    Args:
64        interval_in_sec: The time interval in seconds between each tick
65        on_tick: Callback function that will be called on each tick.
66        loop: The event loop to schedule callbacks on. If None, uses the current loop
67
68    Returns:
69        A task that can be awaited or cancelled to stop the ticker
70    """
71    if loop is None:
72        loop = asyncio.get_running_loop()
73
74    return loop.create_task(_ticker(interval_in_sec, on_tick))
def create_ticker( interval_in_sec: float, on_tick: remotivelabs.topology.time.callback.OnTickCallback, loop: asyncio.events.AbstractEventLoop | None = None) -> _asyncio.Task:
57def create_ticker(interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop | None = None) -> asyncio.Task:
58    """
59    Creates a ticker that calls the on_tick function at the given interval.
60
61    Note that the timer is a best effort timer. The actual interval may be longer than the specified interval if concurrent tasks are
62    unwilling to yield the CPU.
63
64    Args:
65        interval_in_sec: The time interval in seconds between each tick
66        on_tick: Callback function that will be called on each tick.
67        loop: The event loop to schedule callbacks on. If None, uses the current loop
68
69    Returns:
70        A task that can be awaited or cancelled to stop the ticker
71    """
72    if loop is None:
73        loop = asyncio.get_running_loop()
74
75    return loop.create_task(_ticker(interval_in_sec, on_tick))

Creates a ticker that calls the on_tick function at the given interval.

Note that the timer is a best effort timer. The actual interval may be longer than the specified interval if concurrent tasks are unwilling to yield the CPU.

Arguments:
  • interval_in_sec: The time interval in seconds between each tick
  • on_tick: Callback function that will be called on each tick.
  • loop: The event loop to schedule callbacks on. If None, uses the current loop
Returns:

A task that can be awaited or cancelled to stop the ticker