簡體   English   中英

如果有兩個 asyncio.get_event_loop,順序是什么?

[英]what's the order if there are two asyncio.get_event_loop?

有兩件事需要做:托管網站和發送通知。所以我使用以下方法來解決這個問題:

from aiohttp import web
import asyncio


async def _send_proactive_message():
    ...

async def pre_init():
    await asyncio.sleep(20)
    await _send_proactive_message()

APP = web.Application()
APP.router.add_post("/api/messages", messages)
APP.router.add_get("/api/notify", notify)




if __name__ == '__main__':


    event_loop = asyncio.get_event_loop()
    try:
        event_loop.create_task(pre_init())
        web.run_app(APP, host="localhost", port=CONFIG.PORT)

    finally:
        event_loop.close()

因為web.run_app里面有一個event_loop,不明白是哪個先跑,每個event_loop怎么控制。

您在啟動事件循環之前創建任務的方法是可以的,但run_app不會設置並使用另一個事件循環。

更好的方法是在事件循環啟動后創建任務或其他異步對象。 通過這種方式,您將確保創建的對象附加到活動的運行事件循環。

在你的情況下最好的方法是使用on_startup鈎子:

async def pre_init(app):
    await _send_proactive_message()


async def make_app():
    app = web.Application()

    app.router.add_post("/api/messages", messages)
    app.router.add_get("/api/notify", notify)

    app.on_startup.append(pre_init)

    return app


web.run_app(make_app())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM