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

后端 未结 5 942
广开言路
广开言路 2020-11-29 10:52

I\'m writing a discord bot using discord.py rewrite, and I want to run a function every day at a certain time. I\'m not experienced with async functions at all and I can\'t

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 11:11

    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:

    from discord.ext import commands, tasks
    from datetime import datetime, timdelta
    
    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()
    

提交回复
热议问题