How to use django-apscheduler to perform timing tasks in Django

created at 07-17-2021 views: 2

Install package

pip install django-apscheduler

usage

1. Modify the settings.py file in the django project and add the django-apscheduler application in INSTALLED_APPS:

INSTALLED_APPS = [
    ......
    'django_apscheduler',# Perform tasks regularly
]

APSCHEDULER_DATETIME_FORMAT =  "N j, Y, f:s a"  # Default

2. Execute the migration command (create two tables: django_apscheduler_djangojob and django_apscheduler_djangojobexecution):

python manage.py makemigrations
python manage.py migrate

3. Add a reference to the written scheduler in any view.py.

As shown in the figure below: create task.py

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

#Turn on timed work
try:
    # Instantiate the scheduler
    scheduler = BackgroundScheduler()
    # The scheduler uses DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # Set timed tasks, the selection method is interval, and the time interval is 10s
    # Another way is to execute the task at a fixed time from Monday to Friday, the corresponding code is:
    # @register_job(scheduler, 'cron', day_of_week='mon-fri', hour='8', minute='30', second='10',id='task_time')
    @register_job(scheduler,"interval", seconds=10)
    def my_job():
        # Write the task you want to perform here
        pass
    register_events(scheduler)
    scheduler.start()
except Exception as e:
    print(e)
    # Stop the timer if there is an error
    scheduler.shutdown()

Then introduce the scheduler into any views.py, so that every time the Django framework is started, the timing tasks will be started at the same time.

from task import scheduler
Please log in to leave a comment.