Django 1.9 + celery + django-celry 实现定时任务

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.7
pip install django==1.9 django-celery==3.1.17 celery==3.1.23 flower==0.9.2 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
 2 djcelery.setup_loader()
 3 BROKER_URL = ‘redis://localhost:6379‘
 4 CELERYBEAT_SCHEDULER = ‘djcelery.schedulers.DatabaseScheduler‘ # 定时任务
 5 CELERY_RESULT_BACKEND = ‘djcelery.backends.database:DatabaseBackend‘
 6 # CELERY_RESULT_BACKEND = ‘redis://localhost:6379‘
 7 CELERY_ACCEPT_CONTENT = [‘application/json‘]
 8 CELERY_TASK_SERIALIZER = ‘json‘
 9 CELERY_RESULT_SERIALIZER = ‘json‘
10 CELERY_TIMEZONE = ‘Asia/Shanghai‘
11 CELERY_LOG_FILE = os.path.join(os.path.join(os.path.join(BASE_DIR, ‘logs‘), ‘celery‘), ‘celery.log‘)
12 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

时间: 2024-08-13 19:12:36

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

利用celery+django 在admin后台设置定时任务

经常用python开发web应用时,会涉及到定时任务的脚本,以前用linux自带的crontab来操作,但是感觉不太接地气,后来发现用celery+django 可以方便的实现! 安装软件环境如下: python 2.7.5 Django==1.8.2 celery==3.1.18 celery-with-redis==3.0 django-celery==3.1.16 MySQL-python==1.2.3 supervisor==3.1.3 使用pip方式安装完以上软件,并且默认系统已经安装

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

[TOC] 一.引言 Django是python语言下的一个比较热门的Web框架,越来越多的企业和开发者使用Django实现自己的Web服务器.在Web服务器开发过程中,有时候我们不仅仅是要实现Web服务器端和用户端的简单逻辑交互,还要实现一些定时任务.举出以下的例子: 定期删除或缓存Redis数据库的记录 为了追求更高的数据库访问性能,我把Redis作为MySql数据库的缓存.把常访问的数据放在Redis中,然后定时存储到Mysql中.并且把过期的Redis数据删掉.那么这个时候,就需要定时去

Django的celery配置(包括定时任务、队列)

一.安装celery Django项目不需要安装celery这个包,可以直接使用django-celery这个包,,先来安装它,在终端中输入: pip install django-celery 二.安装rabbitmq,建立celery队列 我做的项目用的就是rabbitmq,按道理来说,也是可以用redis作为消息队列的,但是rabbitmq更好,此处不做详细解释,有兴趣的同学的可以去研究下. ubuntu环境下,在终端中输入: sudo apt-get install rabbitmq-s

Django 中使用 Celery

起步 在 <分布式任务队列Celery使用说明> 中介绍了在 Python 中使用 Celery 来实验异步任务和定时任务功能.本文介绍如何在 Django 中使用 Celery. 安装 pip install django-celery 这个命令使用的依赖是 Celery 3.x 的版本,所以会把我之前安装的 4.x 卸载,不过对功能上并没有什么影响.我们也完全可以仅用Celery在django中使用,但使用 django-celery 模块能更好的管理 celery. 使用 可以把有关 C

django 2.x + celery 4.2.x 配置文件 设置

django 2.x + celery 4.2.x配置 模块 celery==4.2.1 django-celery-beat==1.1.1 django-celery-results==1.0.1 kombu==4.2.1 配置 __init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] ce

Django的标准库django.contrib包介绍

前面我们激活了 Django 后台,我们要使用自动化的站点管理工具(django.contrib.admin),所以最好对Django.contrib进行了解,它是啥?它是一个强大的功能包,是Django的标准库. Django的标准库存放在 django.contrib 包中.每个子包都是一个独立的附加功能包. 这些子包一般是互相独立的,不过有些django.contrib子包需要依赖其他子包. 在 django.contrib 中对函数的类型并没有强制要求 .其中一些包中带有模型(因此需要你

django (四) 第一个django app 自动生成admin site

生成管理网站让你的员工或客户添加.更改和删除内容是非常繁琐的工作.出于这个原因,Django完全自动化管理接口模型的创建.Django明确的将“内容发布者”和“公共”网站进行分离.网站管理人员使用该系统添加新闻,事件,体育成绩,等等...显示内容在公共网站.Django为网站管理员创建一个统一的界面来编辑内容. 所以admin并不是给网页浏览者使用的,而是给管理者使用的. 下面,我们将admin应用添加进我们的项目.修改setting.py如下: INSTALLED_APPS = ( 'djan

Django项目实践4 - Django网站管理(后台管理员)

http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类站点, 管理界面 是基础设施中很重要的一部分. 这是以网页和有限的可信任管理者为基础的界面,它能够让你加入,编辑和删除站点内容. 常见的样例: 你能够用这个界面公布博客,后台的站点管理者用它来润色读者提交的内容,你的客户用你给他们建立的界面工具更新新闻并公布在站点上.这些都是使用管理界面的样例. 创

django (五) 第一个django app 创建template,修改admin外观

上一章,我们完成了admin的基本功能,但是,它的外观实在是太丑了,那么接下来,我们就尝试去改变它吧~ 要想改变它就要使用Django的模板系统.由于admin是Django自带的app,所以他用的是Django自带的模板系统. 首先你需要在项目中创建一个模板文件夹,你可以把它放在文件中的任何位置,这里假设路径是mysite/templates 注意:这里的mysite是最外面的文件夹.修改settings.py: TEMPLATE_DIRS = ( r'C:\mysite\templates'

Django项目实践2 - Django模板

http://blog.csdn.net/pipisorry/article/details/45061511 上篇:Django项目实践1 - 创建Django项目 Django模板 {视图和模板对逻辑和显示进行了分隔} 上面是使用 django.http.HttpResponse() 来输出"Hello World!".该方式将数据与视图混合在一起,不符合Django的MVC思想.或者HTML被直接硬编码在 Python 代码之中. html = "<html>