celery可以进行任务异步处理,celery还有一种Celery的常用模式便是执行定期任务. 执行定期任务时, Celery会通过celerybeat进程来完成. Celerybeat会保持运行, 一旦到了某一定期任务需要执行时, Celerybeat便将其加入到queue中. 
配置

那么我们如何让他和django搭配着使用呢

其实很简单拿一个项目来说吧

项目介绍

celery==3.1.23

Django==1.9

django-celery==3.1.17

flower==0.9.2

请严格按照版本安装,否则出现故障请自行解决,版本坑不是你很容易发现的

创建一个虚拟环境

virtualenv my-celery_v1 -p python2.
pip install django==1.9 django-celery==3.1. celery==3.1. flower==0.9. redis
cd my-celery_v1/
source bin/active
django-admin startproject proj
cd proj
python manage.py startapp demoapp

修改配置文件settings.py


INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djcelery',
'demoapp', ]
 1 import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://localhost:6379'
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' # 定时任务
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'
# CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_LOG_FILE = os.path.join(os.path.join(os.path.join(BASE_DIR, 'logs'), 'celery'), 'celery.log')
CELERYBEAT_LOG_FILE = os.path.join(os.path.join(os.path.join(BASE_DIR, 'logs'), 'celery'), 'beat.log')

创建celery.py文件

#!/bin/python
#-*- coding:utf-8 -*- from __future__ import absolute_import import os from celery import Celery,platforms os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
# Specifying the settings here means the celery command line program will know where your Django project is.
# This statement must always appear before the app instance is created, which is what we do next:
from django.conf import settings app = Celery('proj') app.config_from_object('django.conf:settings')
platforms.C_FORCE_ROOT = True
# This means that you don’t have to use multiple configuration files, and instead configure Celery directly from the Django settings.
# You can pass the object directly here, but using a string is better since then the worker doesn’t have to serialize the object. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # With the line above Celery will automatically discover tasks in reusable apps if you define all tasks in a separate tasks.py module.
# The tasks.py should be in dir which is added to INSTALLED_APP in settings.py.
# So you do not have to manually add the individual modules to the CELERY_IMPORT in settings.py. @app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request)) # dumps its own request information

在proj/__init__.py

#!/bin/python
from __future__ import absolute_import # 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']

在项目demoapp/tasks.py

from __future__ import absolute_import

import time
from celery import task from celery import shared_task # from celery.task import tasks
# from celery.task import Task # @task()
@shared_task
def add(x, y):
print "%d + %d = %d" % (x, y, x + y)
return x + y # class AddClass(Task):
# def run(x,y):
# print "%d + %d = %d"%(x,y,x+y)
# return x+y
# tasks.register(AddClass) @shared_task
def mul(x, y):
print "%d * %d = %d" % (x, y, x * y)
return x * y @shared_task
def sub(x, y):
print "%d - %d = %d" % (x, y, x - y)
return x - y @task
def sendmail(mail):
print('sending mail to %s...' % mail)
time.sleep(2.0)
print('mail sent.')
print "------------------------------------"
return mail

运行之前创建logs/celery 日志文件夹同步数据库和创建超级用户

python manage.py migrate
python manage.py createsuperuser

首先启动worker没报错正常

python manage.py celery worker --loglevel=info --settings=proj.settings  --autoreload

启动计划任务

python manage.py celery beat

另外为更好的展示任务执行情况我们还是用了flower作为页面展示,使用5555端口访问

python manage.py celery flower -l info --settings=proj.settings

启动django

django manage.py runserver

执行结果:

更直观的执行结果127.0.0.1:5555

Django 1.9 + celery + django-celry 实现定时任务的更多相关文章

  1. django —— Celery实现异步和定时任务

    1. 环境 python==2.7 djang==1.11.2 # 1.8, 1.9, 1.10应该都没问题 celery-with-redis==3.0 # 需要用到redis作为中间人服务(Bro ...

  2. Django中使用Celery实现定时任务(用djcelery)

    一.引言 Django是python语言下的一个比较热门的Web框架,越来越多的企业和开发者使用Django实现自己的Web服务器.在Web服务器开发过程中,有时候我们不仅仅是要实现Web服务器端和用 ...

  3. django+celery+redis实现运行定时任务

    0.目的 在开发项目中,经常有一些操作时间比较长(生产环境中超过了nginx的timeout时间),或者是间隔一段时间就要执行的任务. 在这种情况下,使用celery就是一个很好的选择.   cele ...

  4. Django + Celery 实现动态配置定时任务

    哈喽,今天给大家分享一篇Django+Celery实现动态配置定时任务,因为最近也是无意间看到一位大佬关于这块的文章,然后自己觉得不错,也想学习写一下,然后最终实现功能是在前端页面统一管理计划任务,大 ...

  5. celery介绍、架构、快速使用、包结构,celery执行异步、延迟、定时任务,django中使用celery,定时更新首页轮播图效果实现,数据加入redis缓存的坑及解决

    今日内容概要 celery介绍,架构 celery 快速使用 celery包结构 celery执行异步任务 celery执行延迟任务 celery执行定时任务 django中使用celery 定时更新 ...

  6. Django 中使用 Celery

    起步 在 <分布式任务队列Celery使用说明> 中介绍了在 Python 中使用 Celery 来实验异步任务和定时任务功能.本文介绍如何在 Django 中使用 Celery. 安装 ...

  7. Django中使用Celery

    一.前言 Celery是一个基于python开发的分布式任务队列,如果不了解请阅读笔者上一篇博文Celery入门与进阶,而做python WEB开发最为流行的框架莫属Django,但是Django的请 ...

  8. Celery简介以及Django中使用celery

    目录 Celery简介 消息中间件 任务执行单元 任务结果存储 使用场景 Celery的安装和配置 Celery执行异步任务 基本使用 延时任务 定时任务 异步处理Django任务 案例: Celer ...

  9. django框架下celery+rabbitmq+flower完成异步任务

    [转载请注明出处:] http://www.cnblogs.com/yukityan/p/8035787.html 环境: ubuntu16.04 64位 安装: sudo apt-get insta ...

  10. Django之使用celery和NGINX生成静态页面实现性能优化

    性能优化原理: 当我们要给client浏览器返回一个页面时,我们需要去数据库查询数据并将数据和基本页面模板渲染形成页面返回给客户端,但如果每一个用户访问时都去查询一次首页的的数据时,当日访问量很大时那 ...

随机推荐

  1. 多条件分类统计group by 显示数目为0的类别

    CREATE TABLE #authorTable(author VARCHAR(50)) INSERT #authorTable SELECT 'peter' UNION SELECT '捌妮' U ...

  2. VUE + vue-cli + webpack 创建新项目(2)

    上一篇其实没写完. 好吧这一篇其实也没啥. 就补充一些上一篇没写完的.(随时害怕笔记本丢失的人) 上一篇写完了登录验证的跳转,这一片首先补充一下接口(?). 在使用axios的过程中,我们家后台表示你 ...

  3. Sed练习

    sed:编辑器 sed:Stream EDitor,行编辑器 用法:        sed [opthon]... ‘script’ inputfile.. scritp:‘地址命令’ 常用选项:   ...

  4. vue-router同路由$router.push不跳转一个简单解决方案

    vue-router同路由$router.push不跳转一个简单解决方案 vue-router跳转一般是这么写: toCurrentPage: function(thisId){ this.$rout ...

  5. linux jpg文件查找木马

    find ./ -type f -name "*.jpg" | xargs grep "eval"

  6. CentOS 7安装部署ELK 6.2.4-SUCCESS

    一.ELK介绍 ELK是三款开源软件的缩写,即:ElasticSearch + Logstash + Kibana.这三个工具组合形成了一套实用.易用的监控架构,可抓取系统日志.apache日志.ng ...

  7. 最小生成树 HDU1301 (kuskal & prim)

    Kruskal:1.边排序,2.按边从小到大连接森林至树   3.并查集 #include <stdio.h> #include <stdlib.h> #include < ...

  8. JAVA基础50题

    package package0530; import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;imp ...

  9. Java 平时作业六

    编写一个 Java 应用程序,使用 Java 的输入输出流技术将 Input.txt 的内容(Input.txt 为文本 文件)逐行读出, 每读出一行就顺序为其添加行号(从 1 开始,逐行递增),并写 ...

  10. Beta阶段冲刺二

    Beta冲刺二 1.团队TSP 团队任务 预估时间 实际时间 完成日期 对数据库的最终完善 120 150 12.2 对学生注册功能的完善--新增触发器 150 140 11.29 对教师注册功能的完 ...