Marcin Bobowski
Marcin Bobowski

Reputation: 1775

Python Asyncio - running multiple infinite loops with different "pauses"

Im trying to figure out how to run multiple infinite loops with asyncio - each loop with it's own delays:

import asyncio

async def do_something(delay, message):
    await asyncio.sleep(delay)
    print(message)

def main():
    loop = asyncio.get_event_loop()
    loop.create_task(do_something(1, "delay equals 1"))  
    loop.create_task(do_something(3, "delay equals 3"))  
    loop.run_forever()
if __name__ == '__main__':
    try:
        main()
    except Exception as f:
        print('main error: ', f)

It returns:

delay equals 1
delay equals 3

and I would suspect it to return:

delay equals 1
delay equals 1
delay equals 1
delay equals 3
delay equals 1
delay equals 1
delay equals 3

(or similar) How should I modify this simple routine?


SOLUTION

async def do_something(delay, message):
    while True:
        await asyncio.sleep(delay)
        print(message)

Upvotes: 1

Views: 1647

Answers (1)

AKX
AKX

Reputation: 169397

There's no reason why a simple task would loop forever.

Depending on what you eventually want to do, you can add a while True: in the async functions, or have them schedule another task at the end.

Upvotes: 2

Related Questions