Issue
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)
Solution
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.
Answered By - AKX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.