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
1from django.core.management.base import BaseCommand
2
3class Command(BaseCommand):
4
5 help = 'Refreshes the covid info in the database'
6
7 def handle(self, *args, **options):
8 self._log_info("Refreshing the covid info")
9 # Run the actual refresh routine
10 self._log_info("Refreshed the covid info")
11
12 def _log_info(self, *msg):
13 full_msg = ' '.join(msg)
14 self.stdout.write(self.style.SUCCESS(full_msg))
By implementing the commands this way, I can easily run them using manage.py
:
1$ ./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:
1from django.core import management
2from apscheduler.schedulers.background import BackgroundScheduler
3
4def hourly_covid_refresh():
5 management.call('refresh_covid')
6
7def start():
8 scheduler = BackgroundScheduler()
9 scheduler.add_job(hourly_covid_refresh, 'cron', minute='0', hour='*', day='*', week='*', month='*')
10 scheduler.start()
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.