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")
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()
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()
Top comments (7)
Short, precise and works perfectly,
The only problem is that the scheduler runs the function "update_something()" two times at a specific time.
It's because of development and deployment.
Add this condition before running your scheduler.
if os.environ.get('RUN_MAIN'):
python manage.py runserver --noreload
solved this issue.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
I know it's been a year since you asked, but there's a package on pypi called "chromedriver_binary". Look it up.
Is there a way to run the jobs as soon as the server starts? then it should follow the defined duration
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.