#: Only add pickle to this list if your broker is secured #: from unwanted access (see userguide/security.html) CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'redis://localhost' CELERY_TASK_SERIALIZER = 'json'
代码文件(./demo/demo/celery.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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', 'demo.settings')
app = Celery('demo') # this ‘demo’ is your 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. app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs. app.autodiscover_tasks()
代码文件(./demo/app/tasks.py)
1 2 3 4 5 6 7 8 9 10 11
import time from celery import Celery
celery_app = Celery('tasks', backend='redis://localhost', broker='redis://localhost') # this is celery settings
# this is a function about need many time @celery_app.task def add(a, b): time.sleep(5) return a + b
5433:C 14 May 11:24:01.463 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo 5433:C 14 May 11:24:01.465 # Redis version=4.0.9, bits=64, commit=00000000, modified=0, pid=5433, just started 5433:C 14 May 11:24:01.465 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf 5433:M 14 May 11:24:01.467 * Increased maximum number of open files to 10032 (it was originally set to 256). _._ _.-``__ ''-._ _.-`` `. `_. ''-._ Redis 4.0.9 (00000000/0) 64 bit .-`` .-```. ```\/ _.,_ ''-._ ( ' , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379 | `-._ `._ / _.-' | PID: 5433 `-._ `-._ `-./ _.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | http://redis.io `-._ `-._`-.__.-'_.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | `-._ `-._`-.__.-'_.-' _.-' `-._ `-.__.-' _.-' `-._ _.-' `-.__.-'
5433:M 14 May 11:24:01.470 # Server initialized 5433:M 14 May 11:24:01.470 * DB loaded from disk: 0.000 seconds 5433:M 14 May 11:24:01.470 * Ready to accept connections ^C5433:signal-handler (1526271328) Received SIGINT scheduling shutdown... 5433:M 14 May 12:15:28.345 # User requested shutdown... 5433:M 14 May 12:15:28.345 * Saving the final RDB snapshot before exiting. 5433:M 14 May 12:15:28.348 * DB saved on disk 5433:M 14 May 12:15:28.348 # Redis is now ready to exit, bye bye...
之后新建终端,执行命令 python manage.py runserver ,之后再新建一个终端,执行命令 celery -A demo worker -l info (注: 此处的demo为Django项目名称),没有看到报错的话,就证明运行成功了。