pip install django-celery-results
pip3 install django-celery-beat
settings.py
INSTALLED_APPS += [
'django_celery_results',
'django_celery_beat'
]
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/2'
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/3'
CELERY_RESULT_BACKEND = 'django_db' #使用django orm 作为结果存储
CELERY_RESULT_SERIALIZER = 'json' # 结果序列化方案
CELERY_IMPORTS = (
'app01.tasks',
)
celery.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:sy
from __future__ import absolute_imports, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_test.settings')
app = Celery('celery_test')
app.config_from_object('django.conf:settings', namespace='CELERY') # 使用CELERY_作为前缀,在settings中写配置
app.autodiscover_tasks() #发现每个app下的tasks.py
tasks.py
# -*- coding:utf8 -*-
from __future__ import absolute_import, unicode_literals
from celery import shared_task
import time
# 这里不再使用@app.task, 而是使用@shared_task, 是指定可以在其他app中也可以调用这个任务
@shared_task
def add(x,y):
print('########## running add #####################')
return x + y
@shared_task
def minus(x,y):
# time.sleep(30)
print('########## running minus #####################')
return x - y
https://github.com/Ran-oops/celery_learning/tree/master/celery_test