[drf] Django Scheduled Tasks with APScheduler and Crontab
- If you need to run certain tasks regularly or at certain time period in a django project, then you can consider using apscheduler or crontab. You can choose either one but I will show you both.
apscheduler
File Structure
INSTALLED_APPS = [
'django_apscheduler',
'jobs'
]
TIME_ZONE = 'Asia/Seoul'
APSCHEDULER_DATETIME_FORMAT = "N j, Y, f:s a"
SCHEDULER_DEFAULT = True
from django.apps import AppConfig
class JobsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'jobs'
def ready(self):
from . import jobs
jobs.schedule()
from apscheduler.schedulers.background import BackgroundScheduler
from django.conf import settings
from app.models import Buyer
def myfunc():
# write whatever task you want to perform
print("HEY")
def schedule():
scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE)
scheduler.add_job(myfunc, 'interval', seconds=1)
scheduler.start()
crontab
File Structure
- place cron.py at the same location as settings.py
pip install django-crontab
INSTALLED_APPS = [
'django_crontab',
]
CRONJOBS = [
('0 0 10 ? * 3#1', 'backend.cron.myfunc', '>> '+ os.path.join(BASE_DIR, 'cron.log')),
]
- -> This way cron.log will be created where manage.py is
from apscheduler.schedulers.background import BackgroundScheduler
from django.conf import settings
from chat.models import Message
from datetime import date, timedelta
def myfunc():
# run task a week ago from today
weekago = date.today() - timedelta(days=7)
m = Message.objects.filter(created__lt=weekago).delete()
return
- If your scheduler is not running after deployment, then install the package in the server. The best part of using apscheduler and crontab packages is that I don't need to configure AWS settings other than this.