https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

Celery 4.0 supports Django 1.8 and newer versions. Please use Celery 3.1 for versions older than Django 1.8

安装celery

pip install celery   #celery
pip install django-celery-beat #celery 具有管理界面的数据库支持的定期任务
pip install django-celery-results  #celery work orm存储结构
pip install flower  #celery监控

配置及编写代码

  1. 配置
    • install_app 新增django_celery_beat和django_celery_results
      INSTALLED_APPS = [
         'django.contrib.admin',
         'django.contrib.auth',
         'django.contrib.contenttypes',
         '...',
         'django_celery_beat',
         'django_celery_results',
         '...'
      ]
      
    • celery配置
         # celery
         CELERY_BROKER_URL = 'redis://127.0.0.1:6379/1'
         CELERYD_MAX_TASKS_PER_CHILD = 3
         CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
         # CELERY_RESULT_BACKEND = 'redis://192.168.251.246:8000/1'
         CELERY_ACCEPT_CONTENT = ['json']
         CELERY_TASK_SERIALIZER = 'json'
         CELERY_TIMEZONE = 'Asia/Shanghai'
         # CELERY_IMPORTS = ('tasks',)
      
    • 同步数据库
          python manage.py makemigrations
          python manage.py migrate
      
  2. 项目目录下创建celery.py : file: proj/proj/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')

app = Celery('proj')

# 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))
  1. 项目的init.py 文件中新增以下配置: proj/proj/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',)
  1. 在app下面创建task.py
- app1/
    - tasks.py
    - models.py
- app2/
    - tasks.py
    - models.py
  1. 创建task
# 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)
  1. 启动
celery -A proj worker -l info
celery -A proj beat -l info
elery flower -A devops --address=127.0.0.1 --port=5555

发表评论

邮箱地址不会被公开。