Discord.py Bot run function at specific time every day Discord.py Bot run function at specific time every day heroku heroku

Discord.py Bot run function at specific time every day


The heroku free plan is Linux. Therefore cron will let you run things at a specific time and /etc/init.d/ will let you run things at start up. It’s a good thing to know your OS.


You can write a function to run periodically on a different thread and check if it's the right time to send your message like this example:

from datetime import datetimeimport threadingdef checkTime():    # This function runs periodically every 1 second    threading.Timer(1, checkTime).start()    now = datetime.now()    current_time = now.strftime("%H:%M:%S")    print("Current Time =", current_time)    if(current_time == '02:11:00'):  # check if matches with the desired time        print('sending message')checkTime()


I know I am late, but this may be helpful for future users.
There is a library called APScheduler which can be used to run functions by setting a cron job (there are other ways too instead of cron. Read more).

A small example will be like:

import discordfrom discord.ext import commandsfrom apscheduler.schedulers.asyncio import AsyncIOSchedulerfrom apscheduler.triggers.cron import CronTriggerclass Scheduler(commands.Cog):    """Schedule commands."""    def __init__(self, bot):        self.bot = bot        # Initialize session        self.session = aiohttp.ClientSession()        # Scheduled events    async def schedule_func(self):    def schedule(self):        # Initialize scheduler        schedule_log = logging.getLogger("apscheduler")        schedule_log.setLevel(logging.WARNING)        job_defaults = {            "coalesce": True,            "max_instances": 5,            "misfire_grace_time": 15,            "replace_existing": True,        }        scheduler = AsyncIOScheduler(job_defaults = job_defaults,                           logger = schedule_log)        # Add jobs to scheduler        scheduler.add_job(self.schedule_func, CronTrigger.from_crontab("0 * * * *"))         # Every hour

And in our main.py file add this (after importing the schedule_jobs.py file obviously):

# Start scheduled commandsscheduler = schedule_jobs.Scheduler(bot).schedule()scheduler.start()