Home > Back-end >  Schedule automated jobs in Django
Schedule automated jobs in Django

Time:08-10

Anyone knows how to schedule a Django script to run at a certain date and time?

Example:

User enters someone’s contact info on frontend, Django backend receives the form data, but doesn’t send the contact an email until 48 hours later.

Anyone has an idea? I saw Cron, but looks like Cron needs to be executed and doesn’t automatically execute on its own? Just need help learning the scheduling feature.

CodePudding user response:

You need to use some background task manager and scheduler.

Celery is for managing and execution tasks and Celery Beat will help to schedule the periodic tasks or cron and will be executed at given time.

CodePudding user response:

Install django-crontab using the below command

 pip install django-crontab
   

In your django project’s settings.py file,

INSTALLED_APPS = [
'django_crontab',
...
] 

Create a file anywhere within your django’s project, for e.g. myapp/cron.py and define the function which you want to be executed automatically via cron

def my_cron_job():
    # your functionality goes here 

Add the following line to your django project’s settings.py file [ This is the every two minute cron job]

CRONJOBS = [
    ('*/2 * * * *', 'myapp.cron.my_cron_job')
]

Add all the defined CRONJOBS

python manage.py crontab add

To get all the active CRONJOBS

python manage.py crontab show

To remove all the defined CRONJOBS

python manage.py crontab remove

To list all active cron

crontab -l
  • Related