Reputation:
I am trying to create a task inside a cog. This is code I currently have,
import discord
import asyncio
import schedule
from discord.ext import commands
class BotTasks(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bg_task = self.loop.create_task(self.mytask())
def job():
print("task")
schedule.every().day.at("19:44").do(job)
async def mytask():
while True:
schedule.run_pending()
await asyncio.sleep(1)
def setup(bot):
bot.add_cog(BotTasks(bot))
I feel the code is correct but the problem is with self.bg_task = self.loop.create_task(self.mytask())
, idk what else to put in place of that.
Thanks.
Upvotes: 0
Views: 2104
Reputation: 15689
You can simply use discord.ext.tasks
from discord.ext import tasks
class BackgroundTasks(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(seconds=5) # <- will do this every 5 seconds
async def my_background_task(self, *args):
# do something
To start it
my_background_task.start(some_arguments) # <- you can put this in a command or in the on_ready event
Here are a few more useful functions
loop.stop()
loop.cancel()
loop.restart()
Reference:
Upvotes: 2