1)
安装
需要安装RabbitMQ、Celery和Django-celery
Celery和Django-celery的安装直接pip就好
2)
修改settings.py
在INSTALLED_APPS中加入app:
INSTALLED_APPS = (
...
'djcelery',
'main', # startapp
}
3)
添加RabbitMQ的配置:
import djcelery
djcelery.setup_loader()
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
#或者
#BROKER_HOST = "localhost"
#BROKER_PORT = 5672
#BROKER_USER = "guest"
#BROKER_PASSWORD = "guest"
#BROKER_VHOST = "/"
4)
创建数据库
$ python manage.py syncdb #default
$ python manage.py migrate djcelery #for south
5)
定义和调用tasks
在app(main)目录下新建文件tasks.py
from celery import task
@task()
def add(x, y):
return x + y
6)
开启worker:
$ python manage.py celery worker --loglevel=info
$ #OR
$ python manage.py celeryd -l info --settings=settings
7)
调用任务:
$ python manage.py shell
In [1]: from main.tasks import add
In [2]: a=add.delay(1,1)
In [3]: a.ready() #worker未开启
Out[3]: False
In [4]: a=add.delay(1,1) #开启worker,重新执行
In [5]: a.ready()
Out[5]: True
In [9]: a.get() #Waits until the task is done and returns the retval.
Out[9]: 2
In [10]: a.successful()
Out[10]: True
8)运行index:$ python app.py 8000 ,运行celery:$ python manage.py celeryd -l info --settings=settings