简体   繁体   中英

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

There are two things need to be done: host website and send notification.So I use the following ways to solve this problems:

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()

Because there is one event_loop in web.run_app, I don't understand which one run first and how to control every event_loop.

Your way to create a task before starting event loop is ok, but only if run_app won't set and use another event loop.

Better way is to create tasks or other async objects once event loop is started. This way you will make sure created objects are attached to an active running event loop.

The best way to do it in your case is to use on_startup hook:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM