多任务不协调py bot



我正在尝试使用discord py进行多任务处理,但是我有一个问题

代码:

@tasks.loop(seconds=10)
async def taskLoop(ctx, something):
await ctx.send(something)
@client.command()
async def startX(ctx, something):

taskLoop.start(ctx, something)
@client.command()
async def endX(ctx):

taskLoop.cancel()
taskLoop.stop()

在不一致的情况下,我像这样开始命令:-startX zzzzzzzzzz
它工作了,每10秒机器人发送" zzzzzzzzzzzzzz">

当我尝试创建一个新任务时(而前一个任务仍在运行),例如:-startX yyyyyyyy
我得到错误:
Command raised an exception: RuntimeError: Task is already launched and is not completed.

显然我理解这是因为其他任务仍在工作,但我看了文档,找不到一种方法来创建多个任务。

有什么解决办法吗?线程可能吗?

你不可能多次开始同一个任务。您可以创建一个"任务生成器"。它将生成并启动任务

started_tasks = []
async def task_loop(ctx, something):  # the function that will "loop"
await ctx.send(something)

def task_generator(ctx, something):
t = tasks.loop(seconds=10)(task_loop)
started_tasks.append(t)
t.start(ctx, something)

@bot.command()
async def start(ctx, something):
task_generator(ctx, something)

@bot.command()
async def stop(ctx):
for t in started_tasks:
t.cancel()

最新更新