How to await a coroutine with an event loop
Asked Answered
C

0

2

I have a coroutine that has an event loop. How should I await that coroutine? I am using Python 3.7.3.

# The coroutine
async def main():
    #
    # This code written using apscheduler.schedulers.asyncio.AsyncIOScheduler
    # which has its *event loop* to run scheduled tasks
    # 
    # However, this code will await another coroutine, e.g.,
    # redis = await aioredis.create_redis('/tmp/redis.sock')

    try:
        asyncio.get_event_loop().run_forever()
    except:
        pass


if __name__ == '__main__':
    asyncio.run(main())

The code only runs the main event loop created by asyncio.run() but not the one by managed by apscheduler.

Update 1

However, if change the code to

# The coroutine
async def main():
    #
    # This code written using apscheduler.schedulers.asyncio.AsyncIOScheduler
    # which has its *event loop* to run scheduled tasks
    # 
    # However, this code will await another coroutine, e.g.,
    # redis = await aioredis.create_redis('/tmp/redis.sock')

    #try:
    #    asyncio.get_event_loop().run_forever()
    #except:
    #    pass


if __name__ == '__main__':
    asyncio.run(main())

The code runs main() once as the event loop managed by apscheduler does not run.

However, if change the code to

# The coroutine
async def main():
    #
    # This code written using apscheduler.schedulers.asyncio.AsyncIOScheduler
    # which has its *event loop* to run scheduled tasks
    # 
    # However, this code will await another coroutine, e.g.,
    # redis = await aioredis.create_redis('/tmp/redis.sock')

    try:
        asyncio.get_event_loop().run_forever()
    except:
        pass


if __name__ == '__main__':
    main()

The complains that the coroutine 'main' was never awaited.

Compensate answered 18/4, 2020 at 15:46 Comment(1)
You await it like any other coroutine by using await? I'm not sure I'm understanding what you are asking. You might want to clarify what the problem was with what you have tried.Sufism

© 2022 - 2025 — McMap. All rights reserved.