If you need to set up scheduled tasks for your Web project using the Django framework, or have users manually set scheduled tasks on the page, this article may help you.

An overview of the

There are three possible ways to implement a scheduled task in Django:

Celery framework

Scheduled task is a special type of distributed task. Django’s distribution is mainly implemented by the Celery framework, a python developed queue of distributed tasks. Since it does not support message storage services per se, a third-party messaging service is required to deliver tasks, typically using Redis.

Advantages:

  1. Celery focuses on real-time operation and can be used in production systems to handle millions of tasks daily and can be used in large projects.
  2. Task scheduling can be performed on distributed machines, processes, and threads.

Disadvantages:

Configuration and use are complex, requiring a Redis database and multiple Python third-party libraries.

django-crontab

You can use cron expressions to set scheduled tasks in the Django framework by downloading a Django-crontab package. I don’t know much about this method, but it doesn’t seem to support Windows and its functions are relatively simple.

django-apscheduler

Simple configuration, complete functions, flexible use, Windows and Linux support, suitable for small and medium-sized projects.

Method of use

The concepts in Django-Apscheduler are the same as those in Python’s scheduled task framework, Apscheduler.

(This article uses Django + mysql architecture)

Install the module

pip install django-apscheduler
Copy the code

configuration

  1. Configure the database information in settings.py (omitted).
  2. Add django-apScheduler to INSTALLED_APPS:
    INSTALLED_APPS = [
        ...
        'django_apscheduler'. ]Copy the code

Perform the migration

python manage.py migrate
Copy the code

Go to the database, and two tables are generated, most of which are exactly what the name suggests.

1. django_apscheduler_djangojob

A table for storing tasks

2. django_apscheduler_djangojobexecution

A table used to store the execution status of a task





use

Create a task

There are roughly two ways to create a task: a decorator and the add_job function.

1. A decorator

Implement code in any view.py (I’m used to opening a new app for timed tasks) :

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

Instantiate the scheduler
scheduler = BackgroundScheduler()
# scheduler uses default DjangoJobStore()
scheduler.add_jobstore(DjangoJobStore(), 'default')

Perform this task at 8:30 every day
@register_job(scheduler, 'cron', id='test', hour=8, minute=30, args=['test'])
def test(s):
    # Specific code to execute
    pass

Register the scheduled task and start
register_events(scheduler)
scheduler.start()
Copy the code

The python manage.py runServer task is stored in the django_apscheduler_djangoJob table and is scheduled to be executed.

parameter

  • Scheduler: Specifies the scheduler
  • Trigger: There are three execution modes: ‘date’, ‘interval’, and ‘cron’.
    • ‘date’ + ‘run_date’ parameter combination, can be implementedA single task.

      Example: 2019-07-07 22:49:00 Executing a task

      @register_job(scheduler, 'date', id='test', run_date='2019-07-07 22:49:00')

      Note: During the test, an error will be reported after the task is executed. The task in the djangoJob table will be deleted from mysql after the task is executed. However, the djangoJobexecution table records the execution result, and a foreign key is associated with the DjangoJob table. Therefore, a foreign key constraint error is displayed when the djangoJobexecution table is deleted. However, the task will be executed and deleted after execution.
    • ‘interval’ + ‘hours’ + ‘minutes’ + ….. Parameter combination, can be achievedSpaced task.

      Example: Perform tasks every three and a half hours

      @register_job(scheduler, 'interval', id='test', hours=3, minutes=30)

      You can also select the seconds and days parameters

      Note: If the task takes 10 seconds to execute and the interval is set to 1 second, it will not give you 10 threads to execute 10 tasks simultaneously. It will miss other tasks until the current one is complete.
    • ‘cron’ + ‘hour’ + ‘minute’+… Parameter combination, can be achievedCron class tasks.

      Example: Work at 8:30 every day

      @register_job(scheduler, 'cron', id='test', hour=8, minute=30)

      You can also select parameters such as day,second, and month.
  • Id: indicates the task name, which will be automatically generated if not transmitted. However, it is recommended to give the task a name in order to suspend, start, or delete the task later. If multiple tasks have the same name, the previous task will be overwritten.
  • Args: List type. Parameters needed to execute the code.
  • Next_run_time: indicates the datetime type. Start time. This parameter is needed if you now create a scheduled task and want to automatically send your girlfriend a wechat message at 3:30 am in 3 days.

There are other parameters that you can look at the source code to see if you are interested.

2. Add_job function

The decorator approach is suitable for writers to create tasks themselves, but if you want the user to enter parameters through the page and submit them to manually create a scheduled task, you need to use the add_job function. Here’s a small example where the front end passes JSON data to the back end and triggers test_add_task to add a task:

import json
from django.http import JsonResponse
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job


scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), 'default')

Interface to the front end
def test_add_task(request):
    if request.method == 'POST':
        content = json.loads(request.body.decode())  # receive parameters
        try:
            start_time = content['start_time']  # user input task start time, '10:00:00'
            start_time = start_time.split(':')
            hour = int(start_time)[0]
            minute = int(start_time)[1]
            second = int(start_time)[2]
            s = content['s']  Receive various parameters to execute the task
            Create task
            scheduler.add_job(test, 'cron', hour=hour, minute=minute, second=second, args=[s])
            code = '200'
            message = 'success'
        except Exception as e:
            code = '400'
            message = e
            
        back = {
            'code': code,
            'message': message
        }
        return JsonResponse(json.dumps(data, ensure_ascii=False), safe=False)
        
# Specific code to execute
def test(s):
    pass
    

register_events(scheduler)
scheduler.start()
Copy the code

This allows the front-end user to manually set the scheduled tasks.

parameter

The same parameters as the decorator, except for the first parameter. If the specific function to execute and the function that calls it are in the same file, you simply pass the function name (as in the example above). But I used to write specific business code to another file, the py written interactive interface function before and after the end, only in this case the parameters passed as a string, the format is: ‘package. The module: some. The object’, namely, the package name. Module: function name

Other features

The Django-ApScheduler framework also provides a number of functions to manipulate scheduled tasks. Such as:

  • Delete the task

    scheduler.remove_job(job_name)
  • Suspended task

    scheduler.pause_job(job_name)
  • Open the task

    scheduler.resume_job(job_name)
  • Modify the task

    scheduler.modify_job(job_name)

    Note: You can only modify the parameters of a task. If you want to modify the execution time, delete the task and create it again.

A table like this can be created on the page, along with a simple front – and back-end interaction to allow users to manage their scheduled tasks themselves:

There are also some auxiliary functions (including display all tasks, display the execution time of tasks, etc.), students can check by themselves. Finally, thanks for reading.