我一直在尝试同时运行两个功能,但一个功能似乎永远无法工作,除非我停止另一个功能。第一个函数每 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()
蟒蛇的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_thread or loop.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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)