如何在不等待 Python 响应的情况下执行异步函数

问题描述 投票:0回答:0

我无法在函数内部执行另一个函数(异步)并在不等待响应的情况下继续

我在谷歌上搜索并尝试使用 asyncio 模块执行任务,但

main
仍在等待
func

的响应
import asyncio
import datetime

async def func(delay):
    print('func started ' + datetime.datetime.now().strftime('%H:%M:%S'))
    await asyncio.sleep(delay)
    print('func finished ' + datetime.datetime.now().strftime('%H:%M:%S'))

async def main():
    print('main started ' + datetime.datetime.now().strftime('%H:%M:%S'))
    async_task = asyncio.get_event_loop().create_task(func(3))
    await async_task
    print('main finished ' + datetime.datetime.now().strftime('%H:%M:%S'))

asyncio.run(main())
>>> main started 13:37:21
>>> func started 13:37:21
>>> func finished 13:37:24
>>> main finished 13:37:24
python task scheduled-tasks python-asyncio
© www.soinside.com 2019 - 2024. All rights reserved.