安装依赖 django-celery-results 和 celery
1 2 3 |
pip install celery pip install django-celery-results |
项目根模块下新建 celery.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') celery_app = Celery('project_name') # 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. celery_app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. celery_app.autodiscover_tasks() |
加载到 __init__.py 中
1 2 3 4 5 |
# This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import celery_app __all__ = ('celery_app',) |
添加配置
1 2 3 4 5 6 7 8 |
INSTALLED_APPS = ( ..., 'django_celery_results', ) # CELERY_BROKER_URL = 'amqp://guest1008611@localhost//' CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'django-db' |
创建相关数据表
1 |
python manage.py migrate django_celery_results |
编写一个示例
在你的任一应用下新建 tasks.py
1 2 3 4 5 6 7 8 9 10 |
import os from celery import shared_task import time @shared_task def add(x, y): time.sleep(10) return x + y |
调用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from django.views.generic import View from django.http import HttpResponse from .tasks import add class Index(View): """ 测试 """ @staticmethod def get(request): """ 处理GET 请求 :param request: :return: """ print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) add.delay(3, 5) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) return HttpResponse('执行完成') |
启动命令
1 2 |
# project_name 是你的项目名称 celery -A project_name worker -l info |
发布评论