我试图运行一个无限循环,每20秒检查一次web服务器,如果它发现了什么,我希望它通过我的discord bot向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
我怀疑我是否应该使用异步线程。但是,我该如何使一个无限循环与我的其余代码并行运行呢?
如果你想将其用于discordbot并使用discord.py,那么你可以使用discord.ext.tasks.loop
或后台任务。
循环示例:此处为
背景任务示例:此处为
这些都不会影响你的机器人,除非你没有使用像requests
或time.sleep()
这样的阻止模块