简体   繁体   中英

How to use python async task without await

I use async create_task to run my task in background, but my_task() method not be executed.

async def my_task():
    print("starting my task...")
    time.sleep(2)
    print("finished my task.")


if __name__ == '__main__':
    print("1111")
    loop = asyncio.get_event_loop()
    loop.create_task(my_task())
    print("2222")

the result is

1111
2222

There is a simple fix for this, but you still need to use await which you cannot avoid because create tasks returns a coroutine

import asyncio

async def my_task():
    print("starting my task...")
    await asyncio.sleep(2)
    print("finished my task.")

if __name__ == '__main__':
    print("1111")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_task())
    # or use can use asyncio.run(my_task())
    print("2222")

EDIT: Made changes for pyfile, instead of notebook, thanks user4815162342 for pointing out

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