如何在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使用三角迭代计算圆周率PI的方法
Mar 20 Python
python如何读写csv数据
Mar 21 Python
使用NumPy和pandas对CSV文件进行写操作的实例
Jun 14 Python
python中reader的next用法
Jul 24 Python
Python机器学习之scikit-learn库中KNN算法的封装与使用方法
Dec 14 Python
python实现tail实时查看服务器日志示例
Dec 24 Python
python时间与Unix时间戳相互转换方法详解
Feb 13 Python
如何学习Python time模块
Jun 03 Python
python 基于DDT实现数据驱动测试
Feb 18 Python
python自动生成sql语句的脚本
Feb 24 Python
python实现socket简单通信的示例代码
Apr 13 Python
解决python存数据库速度太慢的问题
Apr 23 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学习 字符串课件
2008/06/15 PHP
php5.3中连接sqlserver2000的两种方法(com与ODBC)
2012/12/29 PHP
探讨php define()函数及defined()函数使用详解
2013/06/09 PHP
jQuery中ajax的使用与缓存问题的解决方法
2013/12/19 Javascript
关于JavaScript中name的意义冲突示例介绍
2014/05/29 Javascript
利用原生JavaScript获取元素样式只是获取而已
2014/10/08 Javascript
一个超简单的jQuery回调函数例子(分享)
2016/08/08 Javascript
jQuery实现的自适应焦点图效果完整实例
2016/08/24 Javascript
ionic实现带字的toggle滑动组件
2016/08/27 Javascript
js实现楼层导航功能
2017/02/23 Javascript
JS自定义函数实现时间戳转换成date的方法示例
2017/08/27 Javascript
使用html+js+css 实现页面轮播图效果(实例讲解)
2017/09/21 Javascript
vue中如何创建多个ueditor实例教程
2017/11/14 Javascript
Router解决跨模块下的页面跳转示例
2018/01/11 Javascript
Net微信网页开发 使用微信JS-SDK获取当前地理位置过程详解
2019/08/26 Javascript
python创建只读属性对象的方法(ReadOnlyObject)
2013/02/10 Python
介绍Python中几个常用的类方法
2015/04/08 Python
python 遍历字符串(含汉字)实例详解
2017/04/04 Python
django 创建过滤器的实例详解
2017/08/14 Python
Python异常对代码运行性能的影响实例解析
2018/02/08 Python
pycharm的console输入实现换行的方法
2019/01/16 Python
基于OpenCV python3实现证件照换背景的方法
2019/03/22 Python
在Django下测试与调试REST API的方法详解
2019/08/29 Python
python栈的基本定义与使用方法示例【初始化、赋值、入栈、出栈等】
2019/10/24 Python
Python3爬虫中关于中文分词的详解
2020/07/29 Python
浅谈html5之sse服务器发送事件EventSource介绍
2017/08/28 HTML / CSS
马来西亚最好的婴儿商店:Motherhood
2017/09/14 全球购物
实习老师个人总结的自我评价
2013/09/28 职场文书
中专生自我鉴定
2013/12/17 职场文书
创业计划书的内容步骤和要领
2014/01/04 职场文书
商场端午节活动方案
2014/01/29 职场文书
2015年“7.11”世界人口日宣传活动方案
2015/05/06 职场文书
2019经典广告词集锦!
2019/07/02 职场文书
你真的了解redis为什么要提供pipeline功能
2021/06/22 Redis
Redis命令处理过程源码解析
2022/02/12 Redis
悬疑名作《朋友游戏》动画无字ED宣传片 新角色公开
2022/04/13 日漫