【发布时间】:2020-11-06 10:25:47
【问题描述】:
我正在为 Discord 编写一个机器人,它可以创建一个计时器并在它用完时发出通知。使用我现在拥有的代码,机器人会休眠一段时间,然后消息说时间到了。 (使用 discord.py)
@bot.command(name='create')
async def create_schedule(ctx, title: str, mins: float):
await ctx.send(f'Created schedule for {title} in {mins} minutes')
time.sleep(60*mins)
await ctx.send(f'{title} is starting now!')
但问题是我不能同时创建两个计划,因为第二个将被放入队列中,等待第一个完成然后启动计时器。 我试图创建一个新线程并在该线程中休眠,以便我可以接受另一个创建命令,但这不起作用。
async def wait(ctx, title, mins):
time.sleep(int(60*mins))
await ctx.send(f'{title} is starting now!')
@bot.command(name='create')
async def create_schedule(ctx, title: str, mins: float):
await ctx.send(f'Created schedule for {title} in {mins} minutes')
threading.Thread(target=wait, args=(ctx, title, mins)).start()
在我接受另一个命令之前,我不想等待wait() 函数完成。我只想启动计时器,将其放在一边并继续解析其他命令。我怎样才能做到这一点?顺便说一句,wait() 函数有一种显示时间到的方式(ctx.send(f'{title} is starting now!')),因此它不必在计时器完成睡眠后返回任何内容或调用程序的任何其他部分(我不需要希望它在时间结束后做任何其他事情)。
提前致谢
【问题讨论】:
-
不要使用
time.sleep- 它会阻塞异步事件循环。请改用asyncio.sleep。 -
它给了我一个错误,说
wait()从未等待过。 -
你必须做
await asyncio.sleep(60*mins) -
感谢您的帮助。我有点想通了。
标签: python multithreading discord python-asyncio