【问题标题】:Multitasks in discord py botdiscord py bot中的多任务
【发布时间】:2021-11-10 04:38:27
【问题描述】:

我正在尝试使用 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 秒发送一次“zzzzzzzzzz”

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

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

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

【问题讨论】:

  • 我似乎无法重现这一点。我认为这个问题很可能同时调用了 loop.cancel 和 loop.stop。只需使用 loop.stop
  • 问题不在于,是创建新任务,stop()和cancel()是停止。
  • 为什么两者都有?为什么不只有一个
  • 如果我只使用 stop(),bot 总是在 stop 命令之后再发送 1 条消息,因为它已经创建了一个线程来发送这条消息,cancel() 用于取消那个尚未发送。 discordpy.readthedocs.io/en/stable/ext/tasks/…
  • 然后只使用取消而不使用停止

标签: python multithreading discord.py multitasking


【解决方案1】:

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

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()

【讨论】:

  • 成功了。我不知道 2 个不同括号 t = tasks.loop(seconds=10)(task_loop) 中的这种形式的参数,我会进一步研究,谢谢。
  • 是一个装饰器,装饰器返回一个函数,这就是为什么第二个括号
  • 哦,原来如此,我当时都不知道。我会学习的,谢谢xD。
猜你喜欢
  • 2021-06-15
  • 1970-01-01
  • 2021-06-17
  • 2021-06-04
  • 2021-02-07
  • 2021-04-24
  • 2020-07-17
  • 2020-06-27
  • 1970-01-01
相关资源
最近更新 更多