#django #python

In my blog, there are some recurring tasks (such as e.g. the refresh of the Covid19 statistics).

They are implemented as management tasks by implemeting them under the app in covid/management/commands/refresh_covid.py:

covid/management/commands/refresh_covid.py

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    help = 'Refreshes the covid info in the database'

    def handle(self, *args, **options):
        self._log_info("Refreshing the covid info")
        # Run the actual refresh routine
        self._log_info("Refreshed the covid info")

    def _log_info(self, *msg):
        full_msg = ' '.join(msg)
        self.stdout.write(self.style.SUCCESS(full_msg))

By implementing the commands this way, I can easily run them using manage.py:

$ ./manage.py refresh_covid

However, when I want to trigger them manually or execute them automatically using tools such as apscheduler, you need a way to call them from code.

This can be achieved by using the django.core.management module:

from django.core import management
from apscheduler.schedulers.background import BackgroundScheduler

def hourly_covid_refresh():
    management.call('refresh_covid')

def start():
    scheduler = BackgroundScheduler()
    scheduler.add_job(hourly_covid_refresh, 'cron', minute='0', hour='*', day='*', week='*', month='*')
    scheduler.start()