Search code examples
djangoherokuscheduled-tasksschedulerscheduling

How to have a Django app running on Heroku doing a scheduled job using Heroku Scheduler


I am developing a Django app running on Heroku.

In order to update my database with some data coming from a certain API service, I need to periodically run a certain script (let's say myscript).

How can I use Heroku Scheduler to do it?


Solution

  • As already explained here, quick and simple way to answer this question is asking yourself how would you do to run that script periodically, as if you were the scheduler yourself.

    Now, the best way to run a script in your Django app at any moment, it is to create a custom management command and to run it from your command prompt when you need it, like this:

    python manage.py some_custom_command
    

    Then, if you were the scheduler, you would run that command from your command prompt at every time written in the schedule.

    So, a good idea would be to make Heroku Scheduler behave the same. Thus, the aim here is to have Heroku Scheduler run python manage.py some_custom_command at scheduled times.

    Here is how you can do it:

    In your_app directory, create a folder management and then inside it create another folder commands and finally, inside it, create a file some_custom_command.py

    So, just to be clear

    your_app/management/commands/some_custom_command.py

    Then, inside some_custom_command.py insert:

    from django.core.management.base import BaseCommand
    from your_app.path_to_myscript_file import myscript
    
    class Command(BaseCommand):
        def handle(self, *args, **options):
    
            # Put here some script to get the data from api service and store it into your models.
            myscript()
    

    Then go on Heroku > your_app > resources

    In add-ons section select Heroku Scheduler, click on it so that its window opens, then click on add job, select the time you want, insert the command python manage.py some_custom_command and save.