Gabriel Belini
Gabriel Belini

Reputation: 779

How to run a background job every few seconds using django

I would like to know how to execute a function or file every few seconds using django so that I can populate my database with data obtained from this function call.

I need a function to be executed every 5 seconds, this function will scrape a website and save its information into my database, this information will be used by one of my template views to generate a plotly graph.

I've read about Celery and async stuff but couldn't figure out a way to put this into practice.

If someone answers this, please tell me where should I put this job file in my django project or if I should just add a function to an existing file.

Upvotes: 3

Views: 3490

Answers (3)

Tauqeer Afzal
Tauqeer Afzal

Reputation: 1

add app on the top of list step 1. INSTALLED_APPS = [ # default django apps 'django_crontab',

#other apps ]

step 2.

save settings.py and run server

step 3. if you are using in docker than docker-compose build before docker-compose-up

Upvotes: 0

Ben
Ben

Reputation: 905

Something this simple could be achieved as a daemon rather than using a cron or celery etc. Take a look at python-daemon or confusingly, another package with the same name.

Upvotes: 0

Exprator
Exprator

Reputation: 27503

pip install django-crontab

add django_crontab in the installed apps in settings file

create a file called cron.py in the project directory and write the function in this file

in settings.py add the time

CRONJOBS = [
    ('* * * * 5', 'cron.my_scheduled_job')
]

then from terminal

python manage.py crontab add

Upvotes: 2

Related Questions