代码改变世界

单独使用celery

2018-04-09 10:16  ZealouSnesS  阅读(442)  评论(0编辑  收藏  举报

单独使用celery

参考

http://docs.celeryproject.org/en/latest/getting-started/index.html

https://www.jianshu.com/p/f1f2cd1cd491

 

1)定义tasks.py(完成了django中celery.py,settings.py,tasks.py的三者的功能)

调用Celery创建对象,并初始化它的一些信息,其中较重要的信息有名字,broker,backend

一般地broker可以用——

app = Celery('tasks', backend='rpc://', broker='pyamqp://')

app = Celery('tasks', backend='redis://localhost', broker='pyamqp://')

通过app对象的conf属性可以设置该app的一些属性

直接设置属性:

app.conf.task_serializer = 'json'

使用conf.update()设置属性:

app.conf.update(

    task_serializer='json',

    accept_content=['json'],  # Ignore other content

    result_serializer='json',

    timezone='Europe/Oslo',

    enable_utc=True,)

使用py文件设置属性:

 

app.config_from_object('celeryconfig')

 

celeryconfig.py文件:

broker_url = 'pyamqp://'result_backend = 'rpc://'

task_serializer = 'json'result_serializer = 'json'accept_content = ['json']timezone = 'Europe/Oslo'enable_utc = True

 

task_routes = {

    'tasks.add': 'low-priority',}

 

task_annotations = {

    'tasks.add': {'rate_limit': '10/m'}}:

 

定义代码:

from celery import Celeryapp = Celery('tasks', broker='pyamqp://guest@localhost//')@app.taskdef add(x, y):

    return x + y

 

2)使用(在views中使用)

>>> result = add.delay(4, 4):

查看task是否完成:

>>> result.ready()False

获取task结果:

>>> result.get(timeout=1)8

如果task中某处抛出了异常,celery默认向上抛出异常,设置propagate=False可以关闭:

>>> result.get(propagate=False)

如果task中某处抛出了异常,可以使用traceback获取异常信息:

>>> result.traceback?

 

3)运行

$ celery -A tasks worker --loglevel=info

查看celery命令和worker可选项的帮助

$ celery worker --help

$ celery help