Python Asyncio在异步运行两个无限函数时遇到问题 [英] python asyncio having trouble with running two infinite functions asynchronously

本文介绍了Python Asyncio在异步运行两个无限函数时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直试图同时运行两个函数,但其中一个似乎永远不起作用,除非我停止另一个。第一个功能是每30秒发送一封电子邮件(该功能经过自身测试,可以正常工作),第二个功能是每隔5秒打印一条简单的声明。因此,在我看到的每6条Hello Worlds&语句之后,我都会收到一封电子邮件。然而,我从来没有收到过电子邮件,除非我在Run函数中实现了一些东西来停止它,比如在10秒后结束。我希望这两个功能都能无限延续(如果可能的话,不会崩溃)。如有任何帮助,我们不胜感激。

async def timer():
    now = time.time()
    end = now + 30
    #sendmail(name, filepath + "\" + name, receiver)
    while True:
        if time.time() >= end:
            sendmail(name, filepath + "\" + name, receiver)
            now = time.time()
            end = now + 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()

此外,如果有人能够使用多处理或线程模块完成任务,我将有兴趣了解它是如何完成的,因为我已经尝试了这两个模块,但都失败了。 我尝试的示例:

t1 = threading.Thread(target=timer)
t2 = threading.Thread(target=runs)
t1.start()
t2.start()

推荐答案

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

async def timer():
    while True:
        await asyncio.sleep(30)
        sendmail(name, filepath + "\" + name, receiver)

async def runs():
    while True:
        print("Hello World")
        await asyncio.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

这篇关于Python Asyncio在异步运行两个无限函数时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆