2

I want to execute functions at specific time intervals. Based on this answer, I am able to do so using asyncio, but only when the time the functions take is less than the interval. For example, when the function time (wait) is less than interval time:

wait = 2
interval = 4

async def function1(wait):
    await aio.sleep(wait)
    t = round(time.time() - start_time, 1)
    print("time function1 executed:", t)

async def function2():
    t = round(time.time() - start_time, 1)
    print("time function2 executed:", t)

async def scheduler(interval):
    while True:
        t = round(time.time() - start_time, 1)
        print("time functions were scheduled:", t)
        await aio.gather(
                         aio.sleep(interval - (time.time() - start_time) % interval),
                         function1(wait),
                         function2()
                         )

start_time = time.time()
aio.run(scheduler(interval))

I get expected behaviour where functions run at my specified interval (4sec):

time functions were scheduled: 0.0
time function2 executed: 0.0
time function1 executed: 2.0
time functions were scheduled: 4.0
time function2 executed: 4.0
time function1 executed: 6.0
time functions were scheduled: 8.0
time function2 executed: 8.0
time function1 executed: 10.0
time functions were scheduled: 12.0
time function2 executed: 12.0
time function1 executed: 14.0

But when wait > interval:

wait = 5
interval = 4

I get:

time functions were scheduled: 0.0
time function2 executed: 0.0
time function1 executed: 5.0
time functions were scheduled: 5.0
time function2 executed: 5.0
time function1 executed: 10.0
time functions were scheduled: 10.0
time function2 executed: 10.0
time function1 executed: 15.0
time functions were scheduled: 15.0
time function2 executed: 15.0
time function1 executed: 20.1

I am completely new to asyncio and have tried playing around with asyncio.wait_for() (using only a single coroutine function) and asyncio.wait() (for multiple coroutine functions) but I keep getting strange behaviours where the scheduling seems to work, but every so often a load of output from the functions is dumped out... I think it may have something to do with cancelling the over-running functions but I don't understand how to cancel them when the interval is up.

Any help would be greatly appreciated.

  • I am on a Windows machine, and use `import nest_asyncio; nest_asyncio.apply()` to solve conflicts from using asyncio in spyder IDE. – threefrenchhens Feb 17 '22 at 22:12

0 Answers0