Skip to content

Use native asyncio timer for lava-worker main loop

Igor Ponomarev requested to merge lava-worker-asyncio-native-timer into master

Instead of manually calculating the the remaining time in each main loop use the loop.call_later to schedule loop event every ping interval.

Cancel the timer handle and clear event after every loop. The timer handle's cancel() method can be called multiple times even after it was fired and the event.clear() can be called even if event is not set.

Here is a small simulation that demonstrates this new main loop:

import asyncio


async def main_loop() -> None:
    loop = asyncio.get_event_loop()
    event = asyncio.Event()

    async def event_setter() -> None:
        while True:
            await asyncio.sleep(25)
            event.set()

    t = loop.create_task(event_setter())

    while True:
        timer_handle = loop.call_later(20, event.set)
        try:
            print(loop.time(), "Ping!")
            await event.wait()
        finally:
            timer_handle.cancel()
            event.clear()

if __name__ == "__main__":
    asyncio.run(main_loop())

This is the result of running it:

16997.04471305 Ping!
17017.06530856 Ping!  # 20 seconds from timer
17022.049538224 Ping! # Event fired after 5 seconds
17042.068576517 Ping! # 20 seconds from timer
17047.052202411 Ping! # Event fired after 5 seconds because (50s - 45s) = 5s
17067.071888103 Ping!

Merge request reports