如何在Django中设置定时任务的方法示例


Posted in Python onJanuary 18, 2019

Django 作为后端Web开发框架,有时候我们需要用到定时任务来或者固定频次的任务来执行某段代码,这时我们就要用到Celery了。Django中有一个中间件:Django-celery

环境:

  • Python 3.6
  • Django为小于1.8版本
  • Celery为3.1版本

第一步安装:django-celery

pip install django-celery

第二步:配置celery和任务

创建测试django环境:

django-admin.py createproject test
django-admin.py startapp demo

创建好的项目布局如下:

- proj/
 - manage.py
 - proj/
  - __init__.py
  - celery.py
  - settings.py
  - urls.py
 - demo/
  - migrations
  - __init__.py
  - admin.py
  - apps.py
  - models.py
  - tasks.py
  - tests.py
  - views.py

2.1 配置celery.py文件

需要替换的内容,我都在对应的行后提示了,剩下的内容默认就好

创建test/test/celery.py文件,内容如下:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
 
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')  # “proj.settings”替换为你的项目信息:test.settings
 
app = Celery('proj') # 这里的proj替换为你的项目名称:test
 
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#  should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
 
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
 
 
@app.task(bind=True)
def debug_task(self):
  print('Request: {0!r}'.format(self.request))

2.2 配置项目的init.py中配置celery内容

打开test/test/__init_.py文件,添加内容:

from __future__ import absolute_import, unicode_literals
 
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
 
__all__ = ('celery_app',)

2.3 在task.py中添加计划任务

编辑test/demo/task.py文件,添加计划任务,内容如下:

# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
 
 
@shared_task
def add(x, y):
  return x + y
 
 
@shared_task
def mul(x, y):
  return x * y
 
 
@shared_task
def xsum(numbers):
  return sum(numbers)

第三步:任务执行

运行django项目: python manage.py runserver

3.1 后台添加计划任务

访问“http://localhost:8000/admin/”,在celery的管理页面里,选择Periodic tasks,进行任务添加。选择对应的任务,设置定时或者周期时间

3.2 启动定时的celery服务

注意:celery依赖redis服务,需要提前运行redis服务:`redis-server`

# 以下两个命令在不同的shell窗口里执行,需要在django的目录下
python manager.py celery beat -l info  #接收定时任务的命令
python manager.py celery worker -l info #执行定时任务的命令,此shell窗口会看到任务的输入信息

3.3 启动单次的celery服务

注意:celery依赖redis服务,需要提前运行redis服务:`redis-server`

python manager.py shell  # 进到django的shell里
from demo.task import mul, xsum  # 导入task任务
a = mul()
b = xsum()
# 执行a, b会输出信息
a(1,2)
b(1)

PS:django-crontab实现Django定时任务

django-crontab安装:

pip install django-crontab

django-crontab加入:只需要将django-crontab加入到settings.py的INSTALLED_APPS即可。如下代码:

INSTALLED_APPS = (

'django_crontab',

...

)

django-crontab配置:settings.py中加入django-crontab的命令即可:

CRONJOBS = [

  ('47 11 * * *', 'django.core.management.call_command', ['closepoll'],{},'>> /var/run.log'),

]

格式:

参数1:定时 例如47 11 * * * 表示每天的11时47分执行
参数2:方法的python模块路径,如果执行django-admin命令,则写django.core.management.call_command
参数3:方法的位置参数列表(默认值:[]),如果执行django-admin命令,则填写所需执行的命令,例如我们在polls中已经定义过的closepoll
参数4:方法的关键字参数的dict(默认值:{})
参数5:执行log存放位置(即重定向到文件,默认:'')

django-crontab任务加载:

django-crontab任务加载比较简单,只需要运行 python manage.py crontab add 即可

查看已经激活的任务使用 python manage.py crontab show

删除已经有的任务使用 python manage.py crontab remove

如果你修改了任务记得一定要使用 python manage.py crontab add 这个会更新定时任务

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
wxpython 学习笔记 第一天
Mar 16 Python
go语言计算两个时间的时间差方法
Mar 13 Python
Python选择排序、冒泡排序、合并排序代码实例
Apr 10 Python
合并百度影音的离线数据( with python 2.3)
Aug 04 Python
Python创建二维数组实例(关于list的一个小坑)
Nov 07 Python
Python正则表达式实现简易计算器功能示例
May 07 Python
python实现图片压缩代码实例
Aug 12 Python
树莓派3 搭建 django 服务器的实例
Aug 29 Python
Python自动化测试笔试面试题精选
Mar 12 Python
Python urllib.request对象案例解析
May 11 Python
python中 _、__、__xx__()区别及使用场景
Jun 30 Python
Python爬虫实例——scrapy框架爬取拉勾网招聘信息
Jul 14 Python
Python设计模式之工厂方法模式实例详解
Jan 18 #Python
Python设计模式之原型模式实例详解
Jan 18 #Python
基于Python实现迪杰斯特拉和弗洛伊德算法
May 27 #Python
Python中logging实例讲解
Jan 17 #Python
python矩阵/字典实现最短路径算法
Jan 17 #Python
python实现Dijkstra静态寻路算法
Jan 17 #Python
解决在Python编辑器pycharm中程序run正常debug错误的问题
Jan 17 #Python
You might like
分享PHP函数实现数字与文字分页代码
2015/07/28 PHP
PHP文件操作之获取目录下文件与计算相对路径的方法
2016/01/08 PHP
利用PHP访问MySql数据库的逻辑操作以及增删改查的实例讲解
2017/08/30 PHP
php微信开发之图片回复功能
2018/06/14 PHP
phpwind放自动注册方法
2006/12/02 Javascript
firefox中用javascript实现鼠标位置的定位
2007/06/17 Javascript
JS操作select下拉框动态变动(创建/删除/获取)
2013/06/02 Javascript
实例分析javascript中的call()和apply()方法
2014/11/28 Javascript
JS解析XML文件和XML字符串详解
2015/04/17 Javascript
基于jQuery+Cookie实现的防止刷新的在线考试倒计时
2015/06/19 Javascript
JS跨域请求外部服务器的资源
2017/02/06 Javascript
使用vue.js实现checkbox的全选和多个的删除功能
2017/02/17 Javascript
JavaScript数据结构之双向链表定义与使用方法示例
2017/10/27 Javascript
Angular resolve基础用法详解
2018/10/03 Javascript
vux-scroller实现移动端上拉加载功能过程解析
2019/10/08 Javascript
Element Dropdown下拉菜单的使用方法
2020/07/26 Javascript
[01:33:59]真人秀《加油 DOTA》 第六期
2014/09/09 DOTA
[01:18:33]Secret vs VGJ.S Supermajor小组赛C组 BO3 第一场 6.3
2018/06/04 DOTA
[48:48]VGJ.T vs Liquid 2018国际邀请赛小组赛BO2 第二场 8.19
2018/08/21 DOTA
python检测服务器是否正常
2014/02/16 Python
Python常用内置函数总结
2015/02/08 Python
Python通过90行代码搭建一个音乐搜索工具
2015/07/29 Python
python 安装virtualenv和virtualenvwrapper的方法
2017/01/13 Python
Python队列的定义与使用方法示例
2017/06/24 Python
Python多版本开发环境管理工具介绍
2019/07/03 Python
在Django model中设置多个字段联合唯一约束的实例
2019/07/17 Python
您的健身减肥和健康饮食专家:vitafy
2017/06/06 全球购物
Lookfantastic葡萄牙官方网站:欧洲第一大化妆品零售商
2018/03/17 全球购物
什么是SQL Server的确定性函数和不确定性函数
2016/08/04 面试题
买卖车协议书
2014/04/21 职场文书
2014年宣传部个人工作总结
2014/12/06 职场文书
餐馆开业致辞
2015/08/01 职场文书
pytorch 如何使用float64训练
2021/05/24 Python
Python中requests做接口测试的方法
2021/05/30 Python
Python基础数据类型tuple元组的概念与用法
2021/08/02 Python
Python+Selenium实现抖音、快手、B站、小红书、微视、百度好看视频、西瓜视频、微信视频号、搜狐视频、一点号、大风号、趣头条等短视频自动发布
2022/04/13 Python