Introduction to two methods of using scheduled tasks in Django

不言
Release: 2018-09-26 17:53:23
Original
2986 people have browsed it

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
Copy after login

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)
Copy after login

3) Start scheduled task

# 启动定时任务
sched.start()
Copy after login

Method 2: django-crontab
1) Installation:

pip install django-crontab
Copy after login

2) Add configuration to INSTALL_APPS
INSTALLED_APPS = (

'django_crontab',
Copy after login

)
3) Write timing function:

在django的app中新建一个test_crontab.py文件,把需要定时执行的代码放进去
Copy after login
    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)
Copy after login

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)
Copy after login

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'),
]
Copy after login

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脚本或者命令
Copy after login

Example:

0 6 * * * commands >> /tmp/test.log # 每天早上6点执行, 并将信息追加到test.log中
0 */2 * * * commands # 每隔2小时执行一次
Copy after login

Interested friends can study the crontab scheduled task of Linux in depth.

6) Add and start a scheduled task

python manage.py crontab add
Copy after login

Other commands:

python manage.py crontab show: 显示当前的定时任务
python manage.py crontab remove: 删除所有定时任务
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template