标签:sch stat 还需要 场景 info 自动 tar div whether
本节内容
Celery介绍和基本使用
启用多个workers
Celery 定时任务
与django结合
通过django配置celery periodic task
Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考虑使用celery, 举几个实例场景中可用的例子:
Celery 在执行任务时需要通过一个消息中间件来接收和发送任务消息,以及存储任务结果, 一般使用rabbitMQ or Redis,后面会讲
1.1 Celery有以下优点:
Celery基本工作流程图
Celery的默认broker是RabbitMQ, 仅需配置一行就可以
broker_url = ‘amqp://guest:guest@localhost:5672//‘
rabbitMQ 没装的话请装一下,安装看这里 http://docs.celeryproject.org/en/latest/getting-started/brokers/rabbitmq.html#id3
使用Redis做broker也可以
安装redis组件
$ pip install -U "celery[redis]"
配置
Configuration is easy, just configure the location of your Redis database:
app.conf.broker_url = ‘redis://localhost:6379/0‘
Where the URL is in the format of:
redis://:password@hostname:port/db_number
all fields after the scheme are optional, and will default to localhost
on port 6379, using database 0.
如果想获取每个任务的执行结果,还需要配置一下把任务结果存在哪
If you also want to store the state and return values of tasks in Redis, you should configure these settings:
app.conf.result_backend = ‘redis://localhost:6379/0‘
$ pip install celery
创建一个celery application 用来定义你的任务列表
创建一个任务文件就叫tasks.py吧
from celery import Celery app = Celery(‘tasks‘, broker=‘redis://localhost‘, backend=‘redis://localhost‘) @app.task def add(x,y): print("running...",x,y) return x+y
启动Celery Worker来开始监听并执行任务
$ celery -A tasks worker --loglevel=info
调用任务
再打开一个终端, 进行命令行模式,调用任务
>>> from tasks import add >>> add.delay(4, 4)
看你的worker终端会显示收到 一个任务,此时你想看任务结果的话,需要在调用 任务时 赋值个变量
>>> result = add.delay(4, 4)
The ready()
method returns whether the task has finished processing or not:
>>> result.ready()
False
You can wait for the result to complete, but this is rarely used since it turns the asynchronous call into a synchronous one:
>>> result.get(timeout=1)
8
In case the task raised an exception, get()
will re-raise the exception, but you can override this by specifying the propagate
argument:
>>> result.get(propagate=False)
If the task raised an exception you can also gain access to the original traceback:
>>> result.traceback
…
标签:sch stat 还需要 场景 info 自动 tar div whether
原文地址:http://www.cnblogs.com/alex3714/p/6351797.html