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

created at 07-17-2021 views: 2

Install package

pip install django-apscheduler


1. Modify the file in the django project and add the django-apscheduler application in 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 makemigrations
python migrate

3. Add a reference to the written scheduler in any

As shown in the figure below: create

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

#Turn on timed work
    # 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
except Exception as e:
    # Stop the timer if there is an error

Then introduce the scheduler into any, 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.