remotivelabs.topology.time.threaded_ticker
1from __future__ import annotations 2 3import asyncio 4import logging 5import time 6from threading import Timer 7 8from remotivelabs.topology.time.callback import OnTickCallback 9 10_logger = logging.getLogger(__name__) 11 12 13class ThreadedTicker: 14 """ 15 ThreadedTicker provides similar functionality to asyncio.Task for timer-based operations. It calls the on_tick callback at regular 16 intervals. The biggest difference is that ThreadedTicker schedules the callback to run on the event loop, but have no further control 17 over the callback execution. Hence, it cannot compensate for long callback execution times. The upside is that it is guaranteed to run 18 at the specified interval due to the timer being a thread-based solution. However, as mentioned before, if the callback takes longer 19 than the interval, the number of scheduled callbacks will accumulate over time. 20 21 Note that the timer is a best effort timer. The actual interval may be longer than the specified interval due to thread scheduling and 22 callback scheduling time. 23 """ 24 25 def __init__(self, interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop) -> None: 26 self._on_tick = on_tick 27 self._interval = interval_in_sec 28 self._timer: Timer | None = None 29 self._start_time = 0.0 30 self._last_tick = self._start_time 31 self._total_drift = 0.0 32 self._loop = loop 33 34 @property 35 def running(self) -> bool: 36 return self._timer is not None 37 38 def _tick(self) -> None: 39 if not self.running: 40 return 41 42 tick_time = time.monotonic() 43 elapsed_time = tick_time - self._start_time 44 since_last_tick = tick_time - self._last_tick 45 self._total_drift += since_last_tick - self._interval 46 self._last_tick = tick_time 47 48 # We put the callback on the event loop to allow it to run asynchronously 49 async def _callback_task(): 50 stop = await self._on_tick( 51 elapsed_time=elapsed_time, 52 since_last_tick=since_last_tick, 53 total_drift=self._total_drift, 54 interval=self._interval, 55 ) 56 if stop: 57 self.cancel() # cancel the timer if the callback returns False 58 59 self._loop.call_soon_threadsafe(lambda: asyncio.create_task(_callback_task())) 60 61 # Schedule next tick with compensated interval; longer if we're ahead of schedule, shorter if we're behind 62 next_interval = max(0, self._interval - (since_last_tick - self._interval)) 63 self._timer = Timer(next_interval, self._tick) 64 self._timer.start() 65 66 def start(self) -> None: 67 if not self.running: 68 _logger.debug(f"timer scheduled at every {self._interval} seconds") 69 self._start_time = time.monotonic() 70 self._last_tick = self._start_time 71 self._total_drift = 0.0 72 73 # Schedule tick after the first interval 74 self._timer = Timer(self._interval, self._tick) 75 self._timer.start() 76 77 def cancel(self) -> None: 78 if self.running: 79 assert self._timer is not None 80 self._timer.cancel() 81 self._timer.join() 82 self._timer = None 83 _logger.debug("timer cancelled") 84 85 86def create_ticker(interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop | None = None) -> ThreadedTicker: 87 """ 88 Creates a ticker that calls the on_tick function at the given interval. 89 90 Note that the timer is a best effort timer. The actual interval may be longer than the specified interval due to thread scheduling and 91 callback execution time. 92 93 Args: 94 interval_in_sec: The time interval in seconds between each tick. 95 on_tick: Callback coroutine that will be called on each tick. Make sure to handle exceptions in the callback, as they will not be 96 caught by the ticker. 97 loop: The event loop to schedule callbacks on. If None, uses the current loop. 98 """ 99 if loop is None: 100 loop = asyncio.get_running_loop() 101 102 ticker = ThreadedTicker(interval_in_sec, on_tick, loop) 103 ticker.start() 104 return ticker
14class ThreadedTicker: 15 """ 16 ThreadedTicker provides similar functionality to asyncio.Task for timer-based operations. It calls the on_tick callback at regular 17 intervals. The biggest difference is that ThreadedTicker schedules the callback to run on the event loop, but have no further control 18 over the callback execution. Hence, it cannot compensate for long callback execution times. The upside is that it is guaranteed to run 19 at the specified interval due to the timer being a thread-based solution. However, as mentioned before, if the callback takes longer 20 than the interval, the number of scheduled callbacks will accumulate over time. 21 22 Note that the timer is a best effort timer. The actual interval may be longer than the specified interval due to thread scheduling and 23 callback scheduling time. 24 """ 25 26 def __init__(self, interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop) -> None: 27 self._on_tick = on_tick 28 self._interval = interval_in_sec 29 self._timer: Timer | None = None 30 self._start_time = 0.0 31 self._last_tick = self._start_time 32 self._total_drift = 0.0 33 self._loop = loop 34 35 @property 36 def running(self) -> bool: 37 return self._timer is not None 38 39 def _tick(self) -> None: 40 if not self.running: 41 return 42 43 tick_time = time.monotonic() 44 elapsed_time = tick_time - self._start_time 45 since_last_tick = tick_time - self._last_tick 46 self._total_drift += since_last_tick - self._interval 47 self._last_tick = tick_time 48 49 # We put the callback on the event loop to allow it to run asynchronously 50 async def _callback_task(): 51 stop = await self._on_tick( 52 elapsed_time=elapsed_time, 53 since_last_tick=since_last_tick, 54 total_drift=self._total_drift, 55 interval=self._interval, 56 ) 57 if stop: 58 self.cancel() # cancel the timer if the callback returns False 59 60 self._loop.call_soon_threadsafe(lambda: asyncio.create_task(_callback_task())) 61 62 # Schedule next tick with compensated interval; longer if we're ahead of schedule, shorter if we're behind 63 next_interval = max(0, self._interval - (since_last_tick - self._interval)) 64 self._timer = Timer(next_interval, self._tick) 65 self._timer.start() 66 67 def start(self) -> None: 68 if not self.running: 69 _logger.debug(f"timer scheduled at every {self._interval} seconds") 70 self._start_time = time.monotonic() 71 self._last_tick = self._start_time 72 self._total_drift = 0.0 73 74 # Schedule tick after the first interval 75 self._timer = Timer(self._interval, self._tick) 76 self._timer.start() 77 78 def cancel(self) -> None: 79 if self.running: 80 assert self._timer is not None 81 self._timer.cancel() 82 self._timer.join() 83 self._timer = None 84 _logger.debug("timer cancelled")
ThreadedTicker provides similar functionality to asyncio.Task for timer-based operations. It calls the on_tick callback at regular intervals. The biggest difference is that ThreadedTicker schedules the callback to run on the event loop, but have no further control over the callback execution. Hence, it cannot compensate for long callback execution times. The upside is that it is guaranteed to run at the specified interval due to the timer being a thread-based solution. However, as mentioned before, if the callback takes longer than the interval, the number of scheduled callbacks will accumulate over time.
Note that the timer is a best effort timer. The actual interval may be longer than the specified interval due to thread scheduling and callback scheduling time.
26 def __init__(self, interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop) -> None: 27 self._on_tick = on_tick 28 self._interval = interval_in_sec 29 self._timer: Timer | None = None 30 self._start_time = 0.0 31 self._last_tick = self._start_time 32 self._total_drift = 0.0 33 self._loop = loop
67 def start(self) -> None: 68 if not self.running: 69 _logger.debug(f"timer scheduled at every {self._interval} seconds") 70 self._start_time = time.monotonic() 71 self._last_tick = self._start_time 72 self._total_drift = 0.0 73 74 # Schedule tick after the first interval 75 self._timer = Timer(self._interval, self._tick) 76 self._timer.start()
87def create_ticker(interval_in_sec: float, on_tick: OnTickCallback, loop: asyncio.AbstractEventLoop | None = None) -> ThreadedTicker: 88 """ 89 Creates a ticker that calls the on_tick function at the given interval. 90 91 Note that the timer is a best effort timer. The actual interval may be longer than the specified interval due to thread scheduling and 92 callback execution time. 93 94 Args: 95 interval_in_sec: The time interval in seconds between each tick. 96 on_tick: Callback coroutine that will be called on each tick. Make sure to handle exceptions in the callback, as they will not be 97 caught by the ticker. 98 loop: The event loop to schedule callbacks on. If None, uses the current loop. 99 """ 100 if loop is None: 101 loop = asyncio.get_running_loop() 102 103 ticker = ThreadedTicker(interval_in_sec, on_tick, loop) 104 ticker.start() 105 return ticker
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 due to thread scheduling and callback execution time.
Arguments:
- interval_in_sec: The time interval in seconds between each tick.
- on_tick: Callback coroutine that will be called on each tick. Make sure to handle exceptions in the callback, as they will not be caught by the ticker.
- loop: The event loop to schedule callbacks on. If None, uses the current loop.