In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to use apscheduler in django. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Celery framework
Scheduled task is a special type of distributed task. The distribution of Django is mainly implemented by the Celery framework, which is a distributed task queue developed by python. Because it does not support the message storage service itself, a third-party message service is required to deliver the task, typically using Redis.
Advantages:
Celery focuses on real-time operations, can be used in production systems to handle millions of tasks every day, and can be used in large projects.
Task scheduling can be performed on distributed machines, processes, and threads.
Disadvantages:
Configuration and use are complex, requiring Redis databases and multiple python third-party libraries.
Django-crontab
You only need to download a django-crontab package to set up scheduled tasks in the Django framework using cron expressions. I don't know much about this method, but it doesn't seem to support the windows system, and the function is relatively simple.
Django-apscheduler
Simple configuration, complete functions, flexible use, support for windows and linux, suitable for small and medium-sized projects.
Usage
The related concepts in django-apscheduler are the same as those in python's scheduled task framework apscheduler, and students who are interested can refer to them by themselves.
(this article uses django + mysql architecture)
Install the module pip install django-apscheduler
Copy code configuration
First configure the database information in settings.py (briefly).
Add django-apscheduler applications to INSTALLED_APPS:
INSTALLED_APPS = [... 'django_apscheduler',.] perform the migration
Python manage.py migrate went to the database to have a look and generated two tables, most of them as the name implies.
1. Django_apscheduler_djangojob
Table used to store tasks
Job_state: I guess it exists here after serializing the specific execution code and parameters of the task.
2. Django_apscheduler_djangojobexecution
A table used to store the status of task execution
Status: execution statu
Duration: how long did it take to execute
Exception: is there anything unusual?
Use to create a task
There are probably two ways to create a task: the decorator and the add_job function.
1. Decorator
Implement the code in any view.py (I'm used to opening a new app to implement scheduled tasks):
From apscheduler.schedulers.background import BackgroundSchedulerfrom django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
# instantiate the scheduler scheduler = BackgroundScheduler () # the scheduler uses the default DjangoJobStore () scheduler.add_jobstore (DjangoJobStore (), 'default')
# perform this task at 08:30 every day @ register_job (scheduler, 'cron', id='test', hour=8, minute=30,args= [' test']) def test (s): # specific code to be executed pass
# the task of registering a scheduled task and starting the register_events (scheduler) scheduler.start () startup service python manage.py runserver will be stored in the django_apscheduler_ Djangoobb table and executed in accordance with the set timing program.
Parameters.
Scheduler: specify a scheduler
Trigger: there are three ways in which tasks are executed: 'date',' interval', 'cron'.
The parameter combination of 'date' +' run_date' can achieve a single task.
Example: perform a task at 22:49:00 on 2019-07-07
@ register_job (scheduler, 'date', id='test', run_date='2019-07-07 22 purl 4900')
Note: during the personal test, an error will be reported after the task is executed, and the task in the djangojob table will be deleted in the mysql after the task is executed. However, the djangojobexecution table records the execution result, and there is a foreign key associated with the djangojob table, so there is a foreign key constraint error when deleting. However, the task will be executed normally, and will be deleted normally after execution.
'interval' + 'hours' +' minutes' +. The combination of parameters can be used to achieve interval tasks.
Example: perform tasks every three and a half hours
There are also seconds,days parameters to choose from.
Note: if a task needs to execute for 10 seconds and the interval is set to 1 second, it will not give you 10 threads to execute 10 tasks at the same time. It misses other tasks until the current task is completed.
@ register_job (scheduler, 'interval', id='test', hours=3, minutes=30)
'cron' + 'hour' +' minute'+... To implement the task of the cron class
Example: perform a task at 08:30 every day
There are also parameters such as day,second,month that can be selected.
@ register_job (scheduler, 'cron', id='test', hour=8, minute=30)
Id: the name of the task, which will be generated automatically if it is not passed. However, in order to pause, open, delete and other operations later on the task, it is recommended to give a name. And it is unique, if multiple tasks have a single name, the previous tasks will be overwritten.
Args: list type. Parameters required to execute the code.
Next_run_time:datetime type. Start execution time. This parameter is required if you create a scheduled task now and want to automatically send Wechat to your girlfriend at 03:30 in three days' time.
Students who are interested in some other parameters can check the source code to understand.
2. Add_job function
The decorator method is suitable for code writers to create their own tasks, and if you want users to enter parameters through the page and submit to manually create scheduled tasks, you need to use the add_job function.
In the following small example, the front end passes json data to the back end, triggering the test_add_task function to add tasks:
Import jsonfrom django.http import JsonResponsefrom apscheduler.schedulers.background import BackgroundSchedulerfrom django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
Scheduler = BackgroundScheduler () scheduler.add_jobstore (DjangoJobStore (), 'default')
# Interface with the front end
Def test_add_task (request): if request.method = = 'POST': content = json.loads (request.body.decode ()) # receive parameter try: start_time = content [' start_time'] # the task start time entered by the user 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 the 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 be executed
Def test (s): pass
Register_events (scheduler) scheduler.start () so that the scheduled task can be set manually by the front-end user.
Parameters.
The parameters of the decorator are more or less the same, except that the first parameter is different.
If the specific function to be executed and the function that called it are in the same file, you only need to pass the function name (as in the example above).
But I am used to writing the specific business code into another file. In view.py, only the interface functions that interact with each other are written. In this case, the parameter passed is a string and the format is: 'package.module:some.object', is the package name. Modules: function name
Other featur
The django-apscheduler framework also provides a number of functions for operating scheduled tasks. For example:
Delete a task
Scheduler.remove_job (job_name)
Pause the task
Scheduler.pause_job (job_name)
Start the mission.
Scheduler.resume_job (job_name)
Modify task
Scheduler.modify_job (job_name)
Note: modify the task can only modify the parameters, if you want to change the execution time, delete the task and recreate it.
You can make a table like this on the page, coupled with a simple front-end interaction, you can allow users to manage scheduled tasks on their own:
This is how to use apscheduler in the django shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.