Python Asyncio Having Trouble With Running Two Infinite Functions Asynchronously
So I have been trying to run two functions simultaneously but one never seems to work unless I stop the other. The first function is intended to send an email every 30 seconds(func
Solution 1:
Python's async
coroutines are meant for cooperative concurrency. That means that coroutines must actively allow others to run. For simple cases, use await asyncio.sleep
to pause the current coroutine and run others.
asyncdeftimer():
whileTrue:
await asyncio.sleep(30)
sendmail(name, filepath + "\\" + name, receiver)
asyncdefruns():
whileTrue:
print("Hello World")
await asyncio.sleep(5)
asyncdefmain():
await asyncio.gather(timer(), runs())
asyncio.run(main())
Notably, do not use time.sleep
– this blocks the current coroutine, as well as the event loop and all other coroutines.
Similarly, avoid any synchronous code with significant runtime – asyncio
cannot switch to other coroutines while synchronous code runs. If needed, use an asyncio
helper to run synchronous code in a thread, e.g. asyncio.to_thread
or loop.run_in_executor
.
asyncdeftimer():
next_run = time.time()
whileTrue:
# run blocking function in thread to keep event-loop freeawait asyncio.to_thread(sendmail, name, filepath + "\\" + name, receiver)
# pause to run approx every 30 secondsawait asyncio.sleep(next_run - time.time())
next_run += 30
Solution 2:
You can Use await asycio.sleep()
For async wait
import asyncio
asyncdeftimer():
whileTrue:
print("email sent")
await asyncio.sleep(30)
asyncdefruns():
whileTrue:
print("Hello World")
await asyncio.sleep(5)
loop = asyncio.get_event_loop()
loop.create_task(timer())
loop.create_task(runs())
loop.run_forever()
Post a Comment for "Python Asyncio Having Trouble With Running Two Infinite Functions Asynchronously"