


Introduction to two methods of using scheduled tasks in Django
This article brings you an introduction to two methods of using scheduled tasks in Django. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Today we introduce two ways to use scheduled tasks in Django.
Method 1: APScheduler
1) Installation:
pip install apscheduler
2) Use:
from apscheduler.scheduler import Scheduler from django.core.cache import cache # 实例化 sched = Scheduler() # 每30秒执行一次 @sched.interval_schedule(seconds=30) def sched_test(): """ 测试-定时将随机数保存到redis中 :return: """ seed = "123456789" sa = [] for i in range(4): sa.append(random.choice(seed)) code = ''.join(sa) cache.set("test_"+code, code)
3) Start scheduled task
# 启动定时任务 sched.start()
Method 2: django-crontab
1) Installation:
pip install django-crontab
2) Add configuration to INSTALL_APPS
INSTALLED_APPS = (
'django_crontab',
)
3) Write timing function:
在django的app中新建一个test_crontab.py文件,把需要定时执行的代码放进去
import random from django.core.cache import cache def test(): """ 测试-定时将随机数保存到redis中 :return: """ seed = "123456789" sa = [] for i in range(4): sa.append(random.choice(seed)) code = ''.join(sa) cache.set("test_"+code, code)
4) Write scheduled commands
Django has registered a manage.py command for Python modules whose names do not start with an underscore in the management/commands directory under each application in the project. Customize a command as follows: Required Define a Command class that inherits from BaseCommand and implement the handle method.
Write appname/management/commands/test.py file
import random from django.core.management.base import BaseCommand from django.core.cache import cache class Command(BaseCommand): """ 自定义命令 """ def handle(self, *args, **options): """ 自定义命令 :return: """ seed = "123456789" sa = [] for i in range(4): sa.append(random.choice(seed)) code = ''.join(sa) cache.set("test_"+code, code)
After the definition is completed, execute python manage.py test, the handle() function will be executed
5) In settings.py Add configuration in
# 运行定时函数 CRONJOBS = [ ('*/1 * * * *', 'appname.test_crontab.test','>>/home/python/test_crontab.log') ] # 运行定时命令 CRONJOBS = [ ('*/1 * * * *', 'django.core.management.call_command', ['test'], {}, '>> /home/python/test.log'), ]
There are three main parameters above, which respectively represent: scheduled task execution time (interval), scheduled tasks to be executed, appending scheduled task information to the file
For those who are familiar with timing in Linux Students who use task crontab may be very familiar with the syntax of the first parameter above. The above indicates that the code will be executed every 1 minute.
The syntax of the scheduled task crontab in Linux is as follows:
* * * * * command 分钟(0-59) 小时(0-23) 每个月的哪一天(1-31) 月份(1-12) 周几(0-6) shell脚本或者命令
Example:
0 6 * * * commands >> /tmp/test.log # 每天早上6点执行, 并将信息追加到test.log中 0 */2 * * * commands # 每隔2小时执行一次
Interested friends can study the crontab scheduled task of Linux in depth.
6) Add and start a scheduled task
python manage.py crontab add
Other commands:
python manage.py crontab show: 显示当前的定时任务 python manage.py crontab remove: 删除所有定时任务
That’s it for today’s scheduled task. If there are any errors, please feel free to share and correct me!
The above is the detailed content of Introduction to two methods of using scheduled tasks in Django. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.