分享

【Python】Django2.0集成Celery4.1详解

 昵称54185769 2018-06-12

环境准备

  • Python3.6
  • pip install Django==2.0.1
  • pip install celery==4.1.0
  • pip install eventlet (加入协程支持)
  • 安装erlang和rabbitMQ-server

配置settings.py文件

  • 在settings.py文件中添加如下内容
...
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False

CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在settings.py同级目录创建celery.py

  • celery.py
  • 注意替换: project_name
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')

# 注册Celery的APP
app = Celery('project_name')
# 绑定配置文件
app.config_from_object('django.conf:settings', namespace='CELERY')

# 自动发现各个app下的tasks.py文件
app.autodiscover_tasks()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

修改settings.py同级目录的init.py文件

from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app

__all__ = ['celery_app']
  • 1
  • 2
  • 3
  • 4

在某个APP中创建tasks.py文件

  • tasks.py
# -*- coding: utf-8 -*-

from celery.task import task

# 自定义要执行的task任务
@task
def print_hello():
    return 'hello celery and django...'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

配置周期性任务或定时任务

from celery.schedules import crontab
CELERY_BEAT_SCHEDULE = {
    # 周期性任务
    'task-one': {
        'task': 'app.tasks.print_hello',
        'schedule': 5.0, # 每5秒执行一次
        # 'args': ()
    },
    # 定时任务
    'task-two': {
        'task': 'app.tasks.print_hello',
        'schedule': crontab(minute=0, hour='*/3,10-19'),
        # 'args': ()
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

启动worker和定时任务

  • 启动worker (切换到manage.py同级目录下执行)
celery -A project_name worker -l info -P eventlet
  • 1
  • 启动定时任务或周期性任务
celery -A project_name beat -l info
  • 1
  • 这里备注一下:最好使用supervisord来管理上面这2条命令

存放任务结果的扩展

  • pip install django-celery-results
  • Install APP
INSTALLED_APPS = (
    ...,
    'django_celery_results',
)
  • 1
  • 2
  • 3
  • 4
  • 生成数据库表:python manage.py migrate django_celery_results
  • 配置settings:CELERY_RESULT_BACKEND = 'django-db' (用数据库存放任务执行结果信息)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多