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
from django.core.management.base import BaseCommandclass 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 routineself._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 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
from django.core import managementfrom apscheduler.schedulers.background import BackgroundSchedulerdef 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()