如何在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程序中自定义异常的方法
Oct 16 Python
Python编程中的文件读写及相关的文件对象方法讲解
Jan 19 Python
mvc框架打造笔记之wsgi协议的优缺点以及接口实现
Aug 01 Python
wtfPython—Python中一组有趣微妙的代码【收藏】
Aug 31 Python
python scatter散点图用循环分类法加图例
Mar 19 Python
python通过paramiko复制远程文件及文件目录到本地
Apr 30 Python
pycharm编写spark程序,导入pyspark包的3中实现方法
Aug 02 Python
twilio python自动拨打电话,播放自定义mp3音频的方法
Aug 08 Python
Python While循环语句实例演示及原理解析
Jan 03 Python
Python实现投影法分割图像示例(一)
Jan 17 Python
简单了解django文件下载方式
Feb 10 Python
pandas中DataFrame重置索引的几种方法
May 24 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下几个常用的去空、分组、调试数组函数
2009/02/22 PHP
Linux系统下PHP-FPM的安装和配置教程
2015/08/17 PHP
Yii2框架实现数据库常用操作总结
2017/02/08 PHP
详解PHP函数 strip_tags 处理字符串缺陷bug
2017/06/11 PHP
js显示文本框提示文字的方法
2015/05/07 Javascript
javascript实时显示当天日期的方法
2015/05/20 Javascript
Angular+Bootstrap+Spring Boot实现分页功能实例代码
2017/07/21 Javascript
node使用promise替代回调函数
2018/05/07 Javascript
JavaScript封装的常用工具类库bee.js用法详解【经典类库】
2018/09/03 Javascript
Vue快速实现通用表单验证的方法
2020/02/24 Javascript
详解微信小程序动画Animation执行过程
2020/09/23 Javascript
详解js创建对象的几种方式和对象方法
2021/03/01 Javascript
[01:06:26]全国守擂赛第二周 Team Coach vs DeMonsTer
2020/04/28 DOTA
python使用wmi模块获取windows下的系统信息 监控系统
2015/10/27 Python
详解Python中的__getitem__方法与slice对象的切片操作
2016/06/27 Python
Python 正则表达式入门(中级篇)
2016/12/07 Python
python list转矩阵的实例讲解
2018/08/04 Python
Python中作用域的深入讲解
2018/12/10 Python
Python XlsxWriter模块Chart类用法实例分析
2019/03/11 Python
python3.4 将16进制转成字符串的实例
2019/06/12 Python
python实现kNN算法识别手写体数字的示例代码
2019/08/16 Python
纯css3实现宠物小鸡实例代码
2018/10/08 HTML / CSS
canvas实现漂亮的下雨效果的示例
2018/04/18 HTML / CSS
英国婴儿及儿童产品商店:TigerParrot
2019/03/04 全球购物
Rowdy Gentleman服装和配饰:美好时光
2019/09/24 全球购物
优秀本科生求职推荐信
2014/02/24 职场文书
环保公益广告语
2014/03/13 职场文书
节能环保口号
2014/06/12 职场文书
全运会口号
2014/06/20 职场文书
暑假安全教育广播稿
2014/09/10 职场文书
餐饮店长岗位职责
2015/04/14 职场文书
上学路上观后感
2015/06/16 职场文书
你会写报告?产品体验报告到底该怎么写?
2019/08/14 职场文书
高端收音机+蓝牙音箱,JBL TUNER FM带收音蓝牙音箱评测
2021/04/24 无线电
java中为什么说子类的构造方法默认访问的是父类的无参构造方法
2022/04/13 Java/Android
苹果的回收机器人可以通过拆解iPhone获取大量的金和铜并外公布了环境保护最新进展
2022/04/21 数码科技