我们可以使用python的包管理器pip来安装:
pip install -U Celery
也可从官方直接下载安装包:https://pypi.python.org/pypi/celery/
tar xvfz celery-0.0.0.tar.gz
cd celery-0.0.0
python setup.py build
python setup.py install
Celery需要一种解决消息的发送和接受的方式,我们把这种用来存储消息的的中间装置叫做message broker, 也可叫做消息中间人。 作为中间人,我们有几种方案可选择:
1.RabbitMQ
2.Redis
我们首先创建tasks.py模块, 其内容为:
from celery import Celery
# 我们这里案例使用redis作为broker
app = Celery('demo', broker='redis://:332572@127.0.0.1/1')
# 创建任务函数
@app.task
def my_task():
print("任务函数正在执行....")
Celery第一个参数是给其设定一个名字, 第二参数我们设定一个中间人broker, 在这里我们使用Redis作为中间人。my_task函数是我们编写的一个任务函数, 通过加上装饰器app.task, 将其注册到broker的队列中。
现在我们在创建一个worker, 等待处理队列中的任务.打开终端,cd到tasks.py同级目录中,执行命令:
celery -A your_app_name worker --pool=solo -l info
任务加入到broker队列中,以便刚才我们创建的celery workder服务器能够从队列中取出任务并执行。如何将任务函数加入到队列中,可使用delay()。
进入python终端, 执行如下代码:
from tasks import my_task
my_task.delay()