Python Asyncio 无法同时运行两个无限函数



我一直在尝试同时运行两个函数,但除非我停止另一个函数,否则其中一个似乎永远不会起作用。第一个函数每 30 秒发送电子邮件一次,而第二个函数每 5 秒打印一个简单的语句。总之,每 6 个"Hello Worlds"输出应发送一封电子邮件。

但是,除非将打印更改为提前停止,例如在 10 秒后结束,否则我永远不会收到电子邮件。我该怎么做才能让两者同时运行而不停止?

async def timer():
end = time.time() + 30
while True:
if time.time() >= end:
sendmail(name, filepath + "\" + name, receiver)
end = time.time() + 30
async def runs():
while True:
print("Hello World")
time.sleep(5)

loop = asyncio.get_event_loop()
loop.create_task(runs())
loop.create_task(timer())
loop.run_forever()

Python的async协程用于协作并发。这意味着协程必须主动允许其他协程运行。对于简单情况,请使用await asyncio.sleep暂停当前协程并运行其他协程。

async def timer():
while True:
await asyncio.sleep(30)  # instead of `if time.time() >= end:…`
sendmail(name, filepath + "\" + name, receiver)
async def runs():
while True:
print("Hello World")
await asyncio.sleep(5)  # instead of `time.sleep(5)`
async def main():
await asyncio.gather(timer(), runs())
asyncio.run(main())

值得注意的是,不要使用time.sleep– 这会阻塞整个线程,这意味着当前协程以及事件循环和所有其他协程,直到休眠结束。
同样,避免任何具有大量运行时的同步代码 –asyncio同步代码运行时无法切换到其他协程。如果需要,使用asyncio帮助程序在线程中运行同步代码,例如asyncio.to_threadloop.run_in_executor.

async def timer():
next_run = time.time()
while True:
# run blocking function in thread to keep event-loop free
await asyncio.to_thread(
sendmail, name, filepath + "\" + name, receiver
)
# pause to run approx every 30 seconds
await asyncio.sleep(next_run - time.time())
next_run += 30

您可以使用await asycio.sleep()进行异步等待

import asyncio

async def timer():
while True:

print("email sent")
await asyncio.sleep(30)

async def runs():
while True:
print("Hello World")
await asyncio.sleep(5)
loop = asyncio.get_event_loop()
loop.create_task(timer())
loop.create_task(runs())
loop.run_forever()

最新更新