[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

  • create jobs folder
  • created init.py, apps.py, jobs.py inside the jobs folder

settings.py

INSTALLED_APPS = [
    'django_apscheduler',
    'jobs'
]

TIME_ZONE = 'Asia/Seoul'

APSCHEDULER_DATETIME_FORMAT = "N j, Y, f:s a"
SCHEDULER_DEFAULT = True

apps.py

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()

jobs.py

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


pip install django-crontab

settings.py

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

cron.py

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.

Did you find this article valuable?

Support Christy Choi by becoming a sponsor. Any amount is appreciated!