简体   繁体   中英

How to run an asyncio coroutine in background?

I have a aiogram dispatcher instance. Its async function start_polling() is meant to continuously request Telegram API server for updates. 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

I also tried create_task and run_forever but those also freeze the thread.

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. I guess using threads are not an option because that's what I'm trying to avoid using async .

After some researching I'm back with an understanding of asyncio basics. 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. So, no awaits means no async. Awaits give time for other functions to execute.

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