简体   繁体   English

如何在没有等待的情况下使用 python 异步任务

[英]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 create_task 在后台运行我的任务,但 my_task() 方法没有被执行。

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有一个简单的解决方法,但是您仍然需要使用 await,这是无法避免的,因为 create tasks 返回一个协程

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编辑:对 pyfile 进行更改,而不是笔记本,感谢 user4815162342 指出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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