我如何 运行 在不同的线程中无限循环协程?

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 一起使用。但是我如何使无限循环 运行 与我的其余代码并行?

如果你想要这个用于 discord 机器人并使用 discord.py,那么你可以使用 discord.ext.tasks.loop 或后台任务。

循环示例:Here

后台任务示例:Here

None 这将影响您的机器人,直到您不使用像 requeststime.sleep()

这样的阻塞模块