1

Well, this question will surely make the delights of the downvotes brigade and may be tagged as" too broad etc", but it is not!, but precisely because it requires "general" knowledge of how things work, I cannot find an answer in the books I have to ask it.

Having my Django application, yes, I can make it interactive by means of the MVC flow. The issue that I have is when I have methods that are not in connection with an html page (that the user sees) but are methods that are supposed to be running constantly in the background. For example, just to illustrate, imagine a code snippet that queries a DB and sends an email with news every 2 hours. It is just not doing anything because I dont know how to "wake that code snippet up". I dont have that problem if I am writing a desktop application in just python without Django. If I right click and say, run this file, the code will running in the background alright.

Yes, naturally I have heard of cron jobs etc, but so far I see that you can cron-tab a file but how do I crontab a method inside views.py? but I suppose that is not either the way to go. I am find that you downvote it, as long as I get an answer.

thank you

2 Answers2

2

I've been using a combination of commands and cron jobs for that purpose.

Write your command, set up your cronjob:

30 3 * * * /home/ubuntu/project/env/bin/python /home/ubuntu/project/manage.py command_name

Profit.

Dalvtor
  • 3,160
  • 3
  • 21
  • 36
1

If you want to execute periodic tasks in Django, then there are multiple options.

  1. Using Crontab.

There are multiple Django crontab apps are available. (django-crontab)
You just need to add the cron function in your settings file.

CRONJOBS = [
    ('*/5 * * * *', 'myapp.cron.my_scheduler')
] 

cron.py

from myapp.views import send_email

def my_scheduler():
    # add logic
    send_email()
  1. Using Celery Beat

I personally prefer Celery over crontab . You can check it here

Saji Xavier
  • 2,132
  • 16
  • 21