我如何 运行 在不同的线程中无限循环协程?
How do I run an infinitely looping coroutine in a different thread?
我正在尝试 运行 一个无限循环,每 20 秒检查一次网络服务器,如果它发现了什么,我希望它通过我的 discord 机器人向 discord 频道发送消息。但是,我不太确定 asyncio 是如何工作的,因为我没有使用 async/await 太多,也不知道如何实际实现它。
我已经尝试了一些东西:
async def poll():
...
await send()
threading.Thread(target = poll).start()
这失败了,因为我没有 await
poll
功能。如果我不在 async def poll
中包含 async
那显然会失败,因为 await send()
无效。
async def poll():
...
await send()
asyncio.run_coroutine_threadsafe(poll(), asyncio.get_event_loop()) # this freezes the rest of my program and prevents my discord bot from working correctly
asyncio.run_coroutine_threadsafe(poll(), asyncio.new_event_loop()) # this warns me saying "coroutine poll was never awaited" and doesn't seem to execute the loop
我怀疑我是否应该将线程与 asyncio 一起使用。但是我如何使无限循环 运行 与我的其余代码并行?
我正在尝试 运行 一个无限循环,每 20 秒检查一次网络服务器,如果它发现了什么,我希望它通过我的 discord 机器人向 discord 频道发送消息。但是,我不太确定 asyncio 是如何工作的,因为我没有使用 async/await 太多,也不知道如何实际实现它。
我已经尝试了一些东西:
async def poll():
...
await send()
threading.Thread(target = poll).start()
这失败了,因为我没有 await
poll
功能。如果我不在 async def poll
中包含 async
那显然会失败,因为 await send()
无效。
async def poll():
...
await send()
asyncio.run_coroutine_threadsafe(poll(), asyncio.get_event_loop()) # this freezes the rest of my program and prevents my discord bot from working correctly
asyncio.run_coroutine_threadsafe(poll(), asyncio.new_event_loop()) # this warns me saying "coroutine poll was never awaited" and doesn't seem to execute the loop
我怀疑我是否应该将线程与 asyncio 一起使用。但是我如何使无限循环 运行 与我的其余代码并行?