Celery 是一個 基於python開發的分散式非同步消息任務隊列,通過它可以輕鬆的實現任務的非同步處理, 如果你的業務場景中需要用到非同步任務,就可以考慮使用celery, 舉幾個實例場景中可用的例子: 你想對100台機器執行一條批量命令,可能會花很長時間 ,但你不想讓你的程式等著結果返回,而是給你返 ...
Celery 是一個 基於python開發的分散式非同步消息任務隊列,通過它可以輕鬆的實現任務的非同步處理, 如果你的業務場景中需要用到非同步任務,就可以考慮使用celery, 舉幾個實例場景中可用的例子:
- 你想對100台機器執行一條批量命令,可能會花很長時間 ,但你不想讓你的程式等著結果返回,而是給你返回 一個任務ID,你過一段時間只需要拿著這個任務id就可以拿到任務執行結果, 在任務執行ing進行時,你可以繼續做其它的事情。
- 你想做一個定時任務,比如每天檢測一下你們所有客戶的資料,如果發現今天 是客戶的生日,就給他發個簡訊祝福
Celery 在執行任務時需要通過一個消息中間件來接收和發送任務消息,以及存儲任務結果, 一般使用rabbitMQ or Redis
Celery有以下優點:
- 簡單:一單熟悉了celery的工作流程後,配置和使用還是比較簡單的
- 高可用:當任務執行失敗或執行過程中發生連接中斷,celery 會自動嘗試重新執行任務
- 快速:一個單進程的celery每分鐘可處理上百萬個任務
- 靈活: 幾乎celery的各個組件都可以被擴展及自定製
Celery基本工作流程圖
Celery安裝使用
Celery的預設broker是RabbitMQ, 僅需配置一行就可以broker_url
=
'amqp://guest:guest@localhost:5672//'
rabbitMQ 沒裝的話請裝一下 https://www.cnblogs.com/JcrLive/p/12469792.html
redis https://www.cnblogs.com/JcrLive/p/12464962.html
安裝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'
安裝celery模塊 pip install celery task.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 …
在項目中如何使用celery
目錄格式如下
proj
/__init__
.py
/celery
.py
/tasks
.py
from
__future__
import
absolute_import, unicode_literals
from
celery
import
Celery
app
=
Celery(
'proj'
,
broker
=
'localhost'
,
backend
=
'localhost'
,
include
=
[
'proj.tasks'
])
# Optional configuration, see the application user guide.
app.conf.update(
result_expires
=
3600
,
)
if
__name__
=
=
'__main__'
:
app.start()
from __future__ import absolute_import, unicode_literals from .celery import app @app.task def add(x, y): return x + y @app.task def mul(x, y): return x * y @app.task def xsum(*numbers): return sum(*numbers)
啟動worker celery -A proj worker -loglevel info
後臺
celery multi start w1 -A proj -loglevel info
celery multi restart w1 -A proj -loglevel info
celery multi stop w1
celery multi stopwait w1
Celery 定時任務
celery支持定時任務,設定好任務的執行時間,celery就會定時自動幫你執行, 這個定時任務模塊叫celery beat
from
celery
import
Celery
from
celery.schedules
import
crontab
app
=
Celery()
@app
.on_after_configure.connect
def
setup_periodic_tasks(sender,
*
*
kwargs):
# Calls test('hello') every 10 seconds.
sender.add_periodic_task(
10.0
, test.s(
'hello'
), name
=
'add every 10'
)
# Calls test('world') every 30 seconds
sender.add_periodic_task(
30.0
, test.s(
'world'
), expires
=
10
)
# Executes every Monday morning at 7:30 a.m.
sender.add_periodic_task(
crontab(hour
='*'
, minute
='*'
, day_of_week
='friday'
),
test.s(
'Happy Mondays!'
),
)
@app
.task
def
test(arg):
print
(arg)
add_periodic_task 會添加一條定時任務
上面是通過調用函數添加定時任務,也可以像寫配置文件 一樣的形式添加, 下麵是每30s執行的任務
app.conf.beat_schedule
=
{
'add-every-30-seconds'
: {
'task'
:
'tasks.add'
,
'schedule'
:
30.0
,
'args'
: (
16
,
16
)
},
}
app.conf.timezone
=
'UTC'
任務添加好了,需要讓celery單獨啟動一個進程來定時發起這些任務, 註意, 這裡是發起任務,不是執行,這個進程只會不斷的去檢查你的任務計劃, 每發現有任務需要執行了,就發起一個任務調用消息,交給celery worker去執行
celery -A periodic_task beat
啟動celery worker來執行任務 celery -A periodic_task worker
更複雜的定時配置
上面的定時任務比較簡單,只是每多少s執行一個任務,但如果你想要每周一三五的早上8點給你發郵件怎麼辦呢?哈,其實也簡單,用crontab功能,跟linux自帶的crontab功能是一樣的,可以個性化定製任務執行時間
crontab http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
還有更多定時配置方式如下:
Example | Meaning |
crontab() |
Execute every minute. |
crontab(minute=0, hour=0) |
Execute daily at midnight. |
crontab(minute=0, hour='*/3') |
Execute every three hours: midnight, 3am, 6am, 9am, noon, 3pm, 6pm, 9pm. |
|
Same as previous. |
crontab(minute='*/15') |
Execute every 15 minutes. |
crontab(day_of_week='sunday') |
Execute every minute (!) at Sundays. |
|
Same as previous. |
|
Execute every ten minutes, but only between 3-4 am, 5-6 pm, and 10-11 pm on Thursdays or Fridays. |
crontab(minute=0,hour='*/2,*/3') |
Execute every even hour, and every hour divisible by three. This means: at every hour except: 1am, 5am, 7am, 11am, 1pm, 5pm, 7pm, 11pm |
crontab(minute=0, hour='*/5') |
Execute hour divisible by 5. This means that it is triggered at 3pm, not 5pm (since 3pm equals the 24-hour clock value of “15”, which is divisible by 5). |
crontab(minute=0, hour='*/3,8-17') |
Execute every hour divisible by 3, and every hour during office hours (8am-5pm). |
crontab(0, 0,day_of_month='2') |
Execute on the second day of every month. |
|
Execute on every even numbered day. |
|
Execute on the first and third weeks of the month. |
|
Execute on the eleventh of May every year. |
|
Execute on the first month of every quarter. |
上面能滿足你絕大多數定時任務需求了,甚至還能根據潮起潮落來配置定時任務, 具體看 http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#solar-schedules