Celery 异步
一个简单、灵活且可靠、处理大量消息的分布式系统,可以在一台或者多台机器上运行。
单个 Celery 进程每分钟可处理数以百万计的任务。
通过消息进行通信,使用消息队列(broker)在客户端和消费者之间进行协调。
安装Celery
用pip或easy_install安装:
sduo pip install Celery
或者:
sudo easy_install Celery
开始使用 Celery
使用celery包含三个方面:1.定义任务函数。2.运行celery服务。3.客户应用程序的调用
使用Redis作为Broker,安装一个celery-with-redis。
开始编写
# tasks.py
import time
from celery import Celery
celery = Celery('tasks', broker='redis://localhost:6379/0')
@celery.task
def sendmail(mail):
print('sending mail to %s...' % mail['to'])
time.sleep(2.0)
print('mail sent.')
然后启动Celery处理任务:
celery-A tasks worker --loglevel=info
上面的命令实际启动的是Worker,如果再放到后台运行,可以扔给supervisor。
发送任务:
>>> from tasks import sendmail
>sendmail.delay(dice(to='celery@python.org'))