Celery笔记

1. Celery介绍

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.
The execution units, called tasks, are executed concurrently on a single or more worker servers using multiprocessing, Eventlet, or gevent. Tasks can execute asynchronously (in the background) or synchronously (wait until ready).
Celery is used in production systems to process millions of tasks a day.

2. Celery中的基本概念

  1. task: 任务
  2. broker: 中间人、存储任务的队列
  3. worker: 真正执行任务的工作者
  4. backend: 用来存储任务执行后的结果

3. demo演示

安装

pip install celery

演示

* 定义celery对象

在定义这个对象的时候,指定task 、broker、[backend],
示例中,使用的redis

from celery import Celery

celery = Celery('task', broker='redis://127.0.0.1:6379/0', backend='redis://127.0.0.1:6379/0')

* 指定任务

@celery.task
def send_mail():
    print('开始发送邮件...')
    time.sleep(5)
    print('邮件发送结束...')

* 运行Celery-worker 服务,接收任务

celery -A tasks worker --loglevel=info

* 运行任务

运行任务的时候通过方法.delay()来运行任务。

if __name__ == '__main__':
    send_mail.delay()

你可能感兴趣的:(Celery笔记)