'stopping a task discord.py

I've made a Discord bot that loops a task every 15 minutes. I've got it working as intended but now I want to add a command that to stop and start the task. Here's part of my code:

class a(commands.Cog):
def __init__(self, client):
    self.client = client

    @tasks.loop(minutes=15.0)
    async def b(self):
        #do something
        
    b.start(self)
    
    @commands.command(pass_context=True)
    async def stopb(self, ctx):
        b.cancel(self)

def setup(client):
    client.add_cog(a(client))

When I use the command stopb an error is returned saying that that stopb is not defined. I've tried to change the indentation but then the error is that b is not defined. The code above is part of a cog. In my main file I have a command that can load and unload the cogs but this does not stop the task.



Solution 1:[1]

Rather than using the loop decorator, you could make your own task function and add it to the bot's loop. This way you can store the task object which has a cancel function.

class a(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.task = self.client.loop.create_task(self.b())


    async def b(self):
        while True:
            #do something

            await asyncio.sleep(900)
            
    @commands.command(pass_context=True)
    async def stopb(self, ctx):
        self.task.cancel()


def setup(client):
    client.add_cog(a(client))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kaanay03