如何在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 相关文章推荐
初步理解Python进程的信号通讯
Apr 09 Python
在Python中使用__slots__方法的详细教程
Apr 28 Python
python创建进程fork用法
Jun 04 Python
Flask框架中密码的加盐哈希加密和验证功能的用法详解
Jun 07 Python
python破解zip加密文件的方法
May 31 Python
使用Python opencv实现视频与图片的相互转换
Jul 08 Python
python与C、C++混编的四种方式(小结)
Jul 15 Python
Django 实现外键去除自动添加的后缀‘_id’
Nov 15 Python
tensorflow 限制显存大小的实现
Feb 03 Python
Anaconda配置pytorch-gpu虚拟环境的图文教程
Apr 16 Python
解决python便携版无法直接运行py文件的问题
Sep 01 Python
Python Django 后台管理之后台模型属性详解
Apr 25 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
用函数读出数据表内容放入二维数组
2006/10/09 PHP
CI框架简单邮件发送类实例
2016/05/18 PHP
PHP实现转盘抽奖算法分享
2020/04/15 PHP
关于laravel模板中生成URL的几种模式总结
2019/10/18 PHP
基于php伪静态的实现方法解析
2020/07/31 PHP
javascript实现的基于金山词霸网络翻译的代码
2010/01/15 Javascript
基于Jquery的$.cookie()实现跨越页面tabs导航实现代码
2011/03/03 Javascript
jquery自动填充勾选框即把勾选框打上true
2014/03/24 Javascript
Jquery给基本控件的取值、赋值示例
2014/05/23 Javascript
jQuery实现瀑布流的取巧做法分享
2015/01/12 Javascript
黑帽seo劫持程序,js劫持搜索引擎代码
2015/09/15 Javascript
全面解析Bootstrap弹窗的实现方法
2015/12/01 Javascript
jQuery实现的给图片点赞+1动画效果(附在线演示及demo源码下载)
2015/12/31 Javascript
Angular的MVC和作用域
2016/12/26 Javascript
js实现简单的二级联动效果
2017/03/09 Javascript
Vue-cli proxyTable 解决开发环境的跨域问题详解
2017/05/18 Javascript
深入浅析Vue中的slots/scoped slots
2018/04/03 Javascript
js中的深浅拷贝问题简析
2019/05/10 Javascript
vue中keep-alive内置组件缓存的实例代码
2020/04/16 Javascript
Vue3 实现双盒子定位Overlay的示例
2020/12/22 Vue.js
wxpython中Textctrl回车事件无效的解决方法
2016/07/21 Python
python发送邮件实例分享
2017/07/28 Python
python将四元数变换为旋转矩阵的实例
2019/12/04 Python
Python for循环搭配else常见问题解决
2020/02/11 Python
运行Python编写的程序方法实例
2020/10/21 Python
详解HTML5 data-* 自定义属性
2018/01/24 HTML / CSS
详解WebSocket跨域问题解决
2018/08/06 HTML / CSS
英国的潮牌鞋履服饰商店:size?
2019/03/26 全球购物
北大自主招生自荐信
2013/10/19 职场文书
关于迟到的检讨书
2014/01/26 职场文书
高中生综合素质自我评价
2015/03/06 职场文书
企业财务总监岗位职责
2015/04/03 职场文书
旷工辞退通知书
2015/04/17 职场文书
2015年电话销售工作总结范文
2015/04/20 职场文书
酒桌上的开场白
2015/06/01 职场文书
读《钢铁是怎样炼成的》有感:百炼方成钢
2019/11/05 职场文书