Celery(2):celery快速上手使用

簡單使用

github:https://github.com/liaotuo/Celery.git
碼雲:https://gitee.com/liaotuo/Celery.git

新建tasks.py, 文件內容如下

# coding=utf-8
from celery import Celery
# celery 的相關配置
celery = Celery('tasks', broker='redis://localhost:6379/0')
# 具體任務(執行兩個數相加)
@celery.task
def add(x, y):
    return x + y

註冊任務到任務隊列

$ celery -A tasks worker -l info  ### -l info表示loglevel等級爲info級,也可以設爲debug級
  • 輸出如下:已經成功加入到task列表中了
    這裏寫圖片描述

調用task

# 打開python交互式環境
$ python
# 輸入一下兩行代碼
# tasks 爲tasks.py 的路徑(樣例是在同一目錄下)
>>> from tasks import add
>>> add.delay(2,5)
# 返回結果的編號
>>><AsyncResult: 5dc2624e-c898-4702-b510-08b3aec3a440>

可以看到celery 控制檯輸出了任務執行的日誌
這裏寫圖片描述
執行成功,耗時0.000605990000622 結果爲15

實際應用(task與配置分離)

新建python 包 celeryTasks ,目錄如下

celeryTasks/
├── celery.py
├── config.py
├── __init__.py
└── tasks.py

文件內容

celery.py

from __future__ import absolute_import 
from celery import Celery 

app = Celery('myCeleryTasks', include=['myCeleryTasks.tasks']) 
app.config_from_object('myCeleryTasks.config') 

config.py

# config file
from __future__ import absolute_import
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
BROKER_URL = 'redis://127.0.0.1:6379/0'

tasks.py

from __future__ import absolute_import
from myCeleryTasks.celery import app 

@app.task
def add(x, y): 
    return x + y 

註冊task

$ celery -A myCeleryTasks worker -l info

調用

# 進入myCeleryTasks同級目錄
$ python #打開python交互式環境
>>>from myCeleryTasks import add
>>>add.delay(1,2)

輸出效果和“簡單使用”是一樣的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章