Python 如何在discord.py中创建多个循环后台任务(不重写)

Python 如何在discord.py中创建多个循环后台任务(不重写),python,discord.py,python-asyncio,background-task,Python,Discord.py,Python Asyncio,Background Task,我一直在尝试为我的discord.py bot添加一个循环后台任务系统,但一旦一个任务开始运行,它就会阻止其他任务。我试着到处寻找答案,但要么他们使用discord.py的重写版本,要么他们只有一个任务 我试图使任务并行运行,以便所有任务都可以同时运行 这是我的密码: #隐藏导入 类背景任务集合: 定义初始化(self,client:discord.client): self.client=client 异步def启动任务(自): 任务=[] 对于目录中的名称(self): 如果name.sta

我一直在尝试为我的discord.py bot添加一个循环后台任务系统,但一旦一个任务开始运行,它就会阻止其他任务。我试着到处寻找答案,但要么他们使用discord.py的重写版本,要么他们只有一个任务

我试图使任务并行运行,以便所有任务都可以同时运行

这是我的密码:

#隐藏导入
类背景任务集合:
定义初始化(self,client:discord.client):
self.client=client
异步def启动任务(自):
任务=[]
对于目录中的名称(self):
如果name.startswith(“任务”),则:
印刷品(名称)
tasks.append(getattr(self,name))
[等待self.client.loop.create_task(task())为任务中的任务创建任务]
#任务
async def task_1(self):#由于任务是按字母顺序启动的,因此只有该任务才会运行
等待self.client。等待,直到准备就绪()
而不是self.client.is_closed():
等待异步睡眠(60*60)
# ...
异步def任务2(自身):
等待self.client。等待,直到准备就绪()
而不是self.client.is_closed():
等待asyncio.sleep(1)
# ...
异步def任务_3(自身):
等待self.client。等待,直到准备就绪()
而不是self.client.is_closed():
等待异步睡眠(30)
# ...
类MyClient(discord.Client):
定义初始化(自我,**选项):
超级()
self.tasks=背景任务集合(self)
异步def on_就绪(自):
# ...
等待self.tasks.start_tasks()
#处理消息、错误等。

您可能应该在

这来自上面链接的文档:

from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()

谢谢你的回答。我使用自己的命令处理程序,因此它不是
commands.Cog
。在这种情况下,谁能
discord.ext.task
仍然有效?它还能同时处理多个任务吗?我目前使用的是一个效率不高的解决方案。您需要将其功能赋予tasks decorator,如文档中的示例答案所示。然后,您可以通过执行self.task\u name.start()来启动它。另外,如果我给您的答案足够充分,请接受它。