【问题标题】:How to create multiple looping background tasks in discord.py (Not rewrite)如何在 discord.py 中创建多个循环后台任务(不重写)
【发布时间】:2021-04-16 21:32:34
【问题描述】:

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

我正在尝试使任务并行运行,以便所有任务都可以同时运行。

这是我的代码:

# hiding imports

class BackgroundTasksCollection:
    def __init__(self, client: discord.Client):
        self.client = client

    async def start_tasks(self):
        tasks = []
        for name in dir(self):
            if name.startswith("task_"):
                print(name)
                tasks.append(getattr(self, name))

        [await self.client.loop.create_task(task()) for task in tasks]

    # tasks
    async def task_1(self):  # only this will run because the tasks are started in alphabetical order
        await self.client.wait_until_ready()
        while not self.client.is_closed():
            await asyncio.sleep(60 * 60)

            # ...

    async def task_2(self):
        await self.client.wait_until_ready()
        while not self.client.is_closed():
            await asyncio.sleep(1)

            # ...

    async def task_3(self):
        await self.client.wait_until_ready()
        while not self.client.is_closed():
            await asyncio.sleep(30)

            # ...
class MyClient(discord.Client):
    def __init__(self, **options):
        super().__init__(**options)
        self.tasks = BackgroundTasksCollection(self)

    async def on_ready(self):
        # ...
        await self.tasks.start_tasks()
    
    # handle message, errors, etc.

【问题讨论】:

    标签: python discord.py python-asyncio background-task


    【解决方案1】:

    您可能应该查看documentation 中的任务的任务

    这是来自上面链接的文档:

    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.Cogdiscord.ext.task 在这种情况下还能工作吗?它还可以同时处理多个任务吗?我目前正在使用一种不太有效的解决方法。
    • 您需要为其提供任务装饰器的功能,如文档中的示例答案中所示。然后,您可以通过执行 self.task_name.start() 来启动它
    • 另外,如果我给你的答案足够,请采纳。
    猜你喜欢
    • 2021-03-19
    • 2021-03-03
    • 2020-09-07
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多