loop.create_task()使用或发出任务时似乎存在很大的时间差异await。在下面的示例 discord bot 中,输入"!q"任何文本通道几乎都会立即停止 bot,"q"在 python 控制台中输入最多需要 2 分钟。我希望发出的任务以相同的速度执行,就像用 await 发出的一样。我想知道,为什么会有这么大的时差。我是否缺少优先级系统,或者是否有其他方法可以从线程发出异步任务?
示例代码:
import discord, threading
class BotClient(discord.Client):
async def halt(self):
await self.close()
print("[Discord Client stopped]")
async def on_message(self, message):
if message.content == "!q":
await self.halt()
class InteractiveThread(threading.Thread):
def __init__(self, client):
super().__init__()
self.client = client
def run(self):
cmd = input()
if(cmd=="q"):
self.client.loop.create_task(self.client.halt())
client = BotClient()
IAT = InteractiveThread(client)
IAT.start()
client.run(SECRET_DISCORD_TOKEN)
IAT.join()
(SECRET_DISCORD_TOKEN 必须替换为您的令牌)