How can I run an async function using the schedule library?

The built-in solution to this in discord.py is to use the discord.ext.tasks extension. This lets you register a task to be called repeatedly at a specific interval. When the bots start, we’ll delay the start of the loop until the target time, then run the task every 24 hours:

import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta

bot = commands.Bot("!")

@tasks.loop(hours=24)
async def my_task():
    ...

@my_task.before_loop
async def before_my_task():
    hour = 21
    minute = 57
    await bot.wait_until_ready()
    now = datetime.now()
    future = datetime.datetime(now.year, now.month, now.day, hour, minute)
    if now.hour >= hour and now.minute > minute:
        future += timedelta(days=1)
    await asyncio.sleep((future-now).seconds)

my_task.start()

Leave a Comment