uneven
uneven

Reputation: 33

asyncio run two different functions periodically with different intervals

Would it be possible using asyncio to run 2 different functions periodically with different interval for each function f forever?

If yes - could you please provide code example.

import asyncio

async def f1(host,*arg):
    # call every 1 sec
    pass

async def f2(url,*args):
    # call every 2 sec
    pass

Expected output:

00:00 f1 for 1.1.1.1

00:01 f1 for 1.1.1.1

00:02 f2 for 'google.com'

00:02 f1 for 1.1.1.1

00:03 f1 for 1.1.1.1

00:04 f2 for 'google.com'

Upvotes: 3

Views: 2138

Answers (1)

user4815162342
user4815162342

Reputation: 154846

Would it be possible using asyncio to run 2 different functions periodically with different interval for each f forever ?

Sure, just create a coroutine that does it in the "obvious" way, by awaiting the coroutine in an infinite loop with asyncio.sleep() between invocations:

import asyncio, time

async def invoke_forever(period, corofn, *args):
    while True:
        then = time.time()
        await corofn(*args)
        elapsed = time.time() - then
        await asyncio.sleep(period - elapsed)

Scenario described in the question would be set up with something like:

loop = asyncio.get_event_loop()
loop.create_task(invoke_forever(1, f1, 'host1'))
loop.create_task(invoke_forever(2, f2, 'host2'))
loop.run_forever()

You can also use asyncio.gather to combine the two invoke_forever into one awaitable, which allows using the asyncio.run function introduced in Python 3.7:

async def invoke_both():
    await asyncio.gather(invoke_forever(1, f1, 'host1'),
                         invoke_forever(2, f2, 'host2'))

asyncio.run(invoke_both())

Upvotes: 7

Related Questions