简体   繁体   English

如何在后台运行异步协程?

[英]How to run an asyncio coroutine in background?

I have a aiogram dispatcher instance.我有一个 aiogram 调度程序实例。 Its async function start_polling() is meant to continuously request Telegram API server for updates.它的 async function start_polling()旨在不断请求 Telegram API 服务器进行更新。 I don't think it really matters because the following, imo, applies to all coroutines.我认为这并不重要,因为在我看来,以下内容适用于所有协程。 I want to run the coroutine in the background so I can do other things in the thread.我想在后台运行协程,这样我就可以在线程中做其他事情。

dispatcher.start_polling() This throws an error of 'coroutine never awaited' asyncio.get_event_loop().run_until_complete(dp.start_polling()) This takes the thread dispatcher.start_polling()这会抛出 'coroutine never awaited' 的错误asyncio.get_event_loop().run_until_complete(dp.start_polling())这会占用线程

I also tried create_task and run_forever but those also freeze the thread.我也试过create_taskrun_forever但那些也冻结了线程。

I came here from JavaScript so I expected the first code to run the coroutine in 'background' because that's what async is for as I understand.我从 JavaScript 来到这里,所以我希望第一个代码在“后台”运行协程,因为据我所知,这就是async的目的。 I guess using threads are not an option because that's what I'm trying to avoid using async .我想使用线程不是一种选择,因为那是我试图避免使用async的原因。

After some researching I'm back with an understanding of asyncio basics.经过一些研究后,我对 asyncio 基础知识有了一定的了解。 Turns out you can't have async and sync code together, because global sync code will block async flow, instead in global of thread you gotta run asyncio.run(main_func()) and in main_func you should write create_task or gather, depending on the need of result and cooperation.原来你不能同时拥有异步和同步代码,因为全局同步代码会阻塞异步流,而不是在全局线程中你必须运行 asyncio.run(main_func()) 而在 main_func 中你应该编写 create_task 或 gather,这取决于结果和合作的需要。 So, no awaits means no async.所以,没有等待意味着没有异步。 Awaits give time for other functions to execute.等待给其他功能执行时间。

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

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