DEV Community

"edisthgirb"[::-1]
"edisthgirb"[::-1]

Posted on • Edited on

Scheduling tasks using APScheduler in Django

This tutorial deals with showing how to schedule tasks using APScheduler in Django and not with real basics of Python or Django.

Okay, let's start

Installing APScheduler:

Run the following command in the terminal:

pip install apscheduler

Setting up APScheduler:

Let's consider the app is named room.

Adding something_update.py to our app directory:

This is how your room/something_update.py should look:

def update_something():
    print("this function runs every 10 seconds")
Enter fullscreen mode Exit fullscreen mode

Adding updater.py to our app directory:

This is how your room/updater.py should look:

from apscheduler.schedulers.background import BackgroundScheduler
from .something_update import update_something


def start():
    scheduler = BackgroundScheduler()
    scheduler.add_job(update_something, 'interval', seconds=10)
    scheduler.start()
Enter fullscreen mode Exit fullscreen mode

Starting the Updater:

This is how your room/apps.py should look:

from django.apps import AppConfig


class RoomConfig(AppConfig):
    name = 'room'

    def ready(self):
        from . import updater
        updater.start()
Enter fullscreen mode Exit fullscreen mode

Thank you, that's it for this tutorial.

Top comments (7)

Collapse
 
zsmain profile image
Ismail Zouaoui

Short, precise and works perfectly,
The only problem is that the scheduler runs the function "update_something()" two times at a specific time.

Collapse
 
thelostkite profile image
the-lost-kite

It's because of development and deployment.
Add this condition before running your scheduler.
if os.environ.get('RUN_MAIN'):

Collapse
 
prabinsr profile image
Prabin

python manage.py runserver --noreload solved this issue.

Collapse
 
apoorvpandey0 profile image
Apoorv Pandey

How to give a relative path to chromedriver so that I can switch servers without having to change path for driver each time?
Or how to stop redownloading driver when using webdriver manager

Collapse
 
michael446 profile image
Michael Adams

I know it's been a year since you asked, but there's a package on pypi called "chromedriver_binary". Look it up.

Collapse
 
pistone45 profile image
Pistone Junior Sanjama

Is there a way to run the jobs as soon as the server starts? then it should follow the defined duration

Collapse
 
aoulaa profile image
Olim Nizomov

so when i run python3 manage.py runserver --noreload it should work automatically right ? but it's not working for some reasons i did everything as showen.