python celery分布式任務(wù)隊(duì)列的使用詳解
一、Celery介紹和基本使用
Celery 是一個(gè) 基于python開(kāi)發(fā)的分布式異步消息任務(wù)隊(duì)列,通過(guò)它可以輕松的實(shí)現(xiàn)任務(wù)的異步處理, 如果你的業(yè)務(wù)場(chǎng)景中需要用到異步任務(wù),就可以考慮使用celery, 舉幾個(gè)實(shí)例場(chǎng)景中可用的例子:
你想對(duì)100臺(tái)機(jī)器執(zhí)行一條批量命令,可能會(huì)花很長(zhǎng)時(shí)間 ,但你不想讓你的程序等著結(jié)果返回,而是給你返回 一個(gè)任務(wù)ID,你過(guò)一段時(shí)間只需要拿著這個(gè)任務(wù)id就可以拿到任務(wù)執(zhí)行結(jié)果, 在任務(wù)執(zhí)行ing進(jìn)行時(shí),你可以繼續(xù)做其它的事情。
你想做一個(gè)定時(shí)任務(wù),比如每天檢測(cè)一下你們所有客戶的資料,如果發(fā)現(xiàn)今天 是客戶的生日,就給他發(fā)個(gè)短信祝福
Celery 在執(zhí)行任務(wù)時(shí)需要通過(guò)一個(gè)消息中間件來(lái)接收和發(fā)送任務(wù)消息,以及存儲(chǔ)任務(wù)結(jié)果, 一般使用rabbitMQ or Redis,后面會(huì)講
1.1 Celery有以下優(yōu)點(diǎn):
- 簡(jiǎn)單:一單熟悉了celery的工作流程后,配置和使用還是比較簡(jiǎn)單的
- 高可用:當(dāng)任務(wù)執(zhí)行失敗或執(zhí)行過(guò)程中發(fā)生連接中斷,celery 會(huì)自動(dòng)嘗試重新執(zhí)行任務(wù)
- 快速:一個(gè)單進(jìn)程的celery每分鐘可處理上百萬(wàn)個(gè)任務(wù)
- 靈活: 幾乎celery的各個(gè)組件都可以被擴(kuò)展及自定制
Celery基本工作流程圖
1.2 Celery安裝使用
Celery的默認(rèn)broker是RabbitMQ, 僅需配置一行就可以
broker_url = 'amqp://guest:guest@localhost:5672//'
rabbitMQ 沒(méi)裝的話請(qǐng)裝一下
使用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.
如果想獲取每個(gè)任務(wù)的執(zhí)行結(jié)果,還需要配置一下把任務(wù)結(jié)果存在哪
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'
1. 3 開(kāi)始使用Celery啦
安裝celery模塊
pip install celery
創(chuàng)建一個(gè)celery application 用來(lái)定義你的任務(wù)列表
創(chuàng)建一個(gè)任務(wù)文件就叫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
啟動(dòng)Celery Worker來(lái)開(kāi)始監(jiān)聽(tīng)并執(zhí)行任務(wù)
celery -A tasks worker --loglevel=info
調(diào)用任務(wù)
再打開(kāi)一個(gè)終端, 進(jìn)行命令行模式,調(diào)用任務(wù)
from tasks import add add.delay(4, 4) #
看你的worker終端會(huì)顯示收到 一個(gè)任務(wù),此時(shí)你想看任務(wù)結(jié)果的話,需要在調(diào)用 任務(wù)時(shí) 賦值個(gè)變量
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 …
二、在項(xiàng)目中如何使用celery
可以把celery配置成一個(gè)應(yīng)用
目錄格式如下
1 proj/__init__.py 2 /celery.py 3 /tasks.py
proj/celery.py內(nèi)容
from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('proj', broker='amqp://', backend='amqp://', include=['proj.tasks']) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start()
proj/tasks.py中的內(nèi)容
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)
啟動(dòng)worker
celery -A proj worker -l info #
輸出
-------------- celery@Alexs-MacBook-Pro.local v4.0.2 (latentcall) ---- **** ----- --- * *** * -- Darwin-15.6.0-x86_64-i386-64bit 2017-01-26 21:50:24 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: proj:0x103a020f0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery
后臺(tái)啟動(dòng)worker
In the background
In production you'll want to run the worker in the background, this is described in detail in the daemonization tutorial.
The daemonization scripts uses the celery multi command to start one or more workers in the background:
$ celery multi start w1 -A proj -l info celery multi v4.0.0 (latentcall) > Starting nodes... > w1.halcyon.local: OK
You can restart it too:
$ celery multi restart w1 -A proj -l info celery multi v4.0.0 (latentcall) > Stopping nodes... > w1.halcyon.local: TERM -> 64024 > Waiting for 1 node..... > w1.halcyon.local: OK > Restarting node w1.halcyon.local: OK celery multi v4.0.0 (latentcall) > Stopping nodes... > w1.halcyon.local: TERM -> 64052
or stop it:
$ celery multi stop w1 -A proj -l info
The stop command is asynchronous so it won't wait for the worker to shutdown. You'll probably want to use the stopwait command instead, this ensures all currently executing tasks is completed before exiting:
$ celery multi stopwait w1 -A proj -l info
三、Celery 定時(shí)任務(wù)
celery支持定時(shí)任務(wù),設(shè)定好任務(wù)的執(zhí)行時(shí)間,celery就會(huì)定時(shí)自動(dòng)幫你執(zhí)行, 這個(gè)定時(shí)任務(wù)模塊叫celery beat
寫(xiě)一個(gè)腳本 叫periodic_task.py
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=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg)
add_periodic_task 會(huì)添加一條定時(shí)任務(wù)
上面是通過(guò)調(diào)用函數(shù)添加定時(shí)任務(wù),也可以像寫(xiě)配置文件 一樣的形式添加, 下面是每30s執(zhí)行的任務(wù)
app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': 30.0, 'args': (16, 16) }, } app.conf.timezone = 'UTC'
任務(wù)添加好了,需要讓celery單獨(dú)啟動(dòng)一個(gè)進(jìn)程來(lái)定時(shí)發(fā)起這些任務(wù), 注意, 這里是發(fā)起任務(wù),不是執(zhí)行,這個(gè)進(jìn)程只會(huì)不斷的去檢查你的任務(wù)計(jì)劃, 每發(fā)現(xiàn)有任務(wù)需要執(zhí)行了,就發(fā)起一個(gè)任務(wù)調(diào)用消息,交給celery worker去執(zhí)行
啟動(dòng)任務(wù)調(diào)度器 celery beat
celery -A periodic_task beat
輸出like below
celery beat v4.0.2 (latentcall) is starting. __ - ... __ - _ LocalTime -> 2017-02-08 18:39:31 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%WARNING . maxinterval -> 5.00 minutes (300s
此時(shí)還差一步,就是還需要啟動(dòng)一個(gè)worker,負(fù)責(zé)執(zhí)行celery beat發(fā)起的任務(wù)
啟動(dòng)celery worker來(lái)執(zhí)行任務(wù)
$ celery -A periodic_task worker -------------- celery@Alexs-MacBook-Pro.local v4.0.2 (latentcall) ---- **** ----- --- * *** * -- Darwin-15.6.0-x86_64-i386-64bit 2017-02-08 18:42:08 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: tasks:0x104d420b8 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery
好啦,此時(shí)觀察worker的輸出,是不是每隔一小會(huì),就會(huì)執(zhí)行一次定時(shí)任務(wù)呢!
注意:Beat needs to store the last run times of the tasks in a local database file (named celerybeat-schedule by default), so it needs access to write in the current directory, or alternatively you can specify a custom location for this file:
celery -A periodic_task beat -s /home/celery/var/run/celerybeat-schedule
更復(fù)雜的定時(shí)配置
上面的定時(shí)任務(wù)比較簡(jiǎn)單,只是每多少s執(zhí)行一個(gè)任務(wù),但如果你想要每周一三五的早上8點(diǎn)給你發(fā)郵件怎么辦呢?哈,其實(shí)也簡(jiǎn)單,用crontab功能,跟linux自帶的crontab功能是一樣的,可以個(gè)性化定制任務(wù)執(zhí)行時(shí)間
from celery.schedules import crontab app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-monday-morning': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, }
上面的這條意思是每周1的早上7.30執(zhí)行tasks.add任務(wù)
還有更多定時(shí)配置方式如下:
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. |
上面能滿足你絕大多數(shù)定時(shí)任務(wù)需求了,甚至還能根據(jù)潮起潮落來(lái)配置定時(shí)任務(wù)
四、最佳實(shí)踐之與django結(jié)合
django 可以輕松跟celery結(jié)合實(shí)現(xiàn)異步任務(wù),只需簡(jiǎn)單配置即可
If you have a modern Django project layout like:
- proj/ - proj/__init__.py - proj/settings.py - proj/urls.py - manage.py
then the recommended way is to create a new proj/proj/celery.py module that defines the Celery instance:
file: proj/proj/celery.py
from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
Then you need to import this app in your proj/proj/__init__.py module. This ensures that the app is loaded when Django starts so that the @shared_task decorator (mentioned later) will use it:
proj/proj/__init__.py:
from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app']
Note that this example project layout is suitable for larger projects, for simple projects you may use a single contained module that defines both the app and tasks, like in the First Steps with Celery tutorial.
Let's break down what happens in the first module, first we import absolute imports from the future, so that our celery.py module won't clash with the library:
from __future__ import absolute_import
Then we set the default DJANGO_SETTINGS_MODULE environment variable for the celery command-line program:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
You don't need this line, but it saves you from always passing in the settings module to the celery program. It must always come before creating the app instances, as is what we do next:
app = Celery('proj')
This is our instance of the library.
We also add the Django settings module as a configuration source for Celery. This means that you don't have to use multiple configuration files, and instead configure Celery directly from the Django settings; but you can also separate them if wanted.
The uppercase name-space means that all Celery configuration options must be specified in uppercase instead of lowercase, and start with CELERY_, so for example the task_always_eager` setting becomes CELERY_TASK_ALWAYS_EAGER, and the broker_url setting becomes CELERY_BROKER_URL.
You can pass the object directly here, but using a string is better since then the worker doesn't have to serialize the object.
app.config_from_object('django.conf:settings', namespace='CELERY')
Next, a common practice for reusable apps is to define all tasks in a separate tasks.pymodule, and Celery does have a way to auto-discover these modules:
app.autodiscover_tasks()
With the line above Celery will automatically discover tasks from all of your installed apps, following the tasks.py convention:
- app1/ - tasks.py - models.py - app2/ - tasks.py - models.py
Finally, the debug_task example is a task that dumps its own request information. This is using the new bind=True task option introduced in Celery 3.1 to easily refer to the current task instance.
然后在具體的app里的tasks.py里寫(xiě)你的任務(wù)
# Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers)
在你的django views里調(diào)用celery task
from django.shortcuts import render,HttpResponse # Create your views here. from bernard import tasks def task_test(request): res = tasks.add.delay(228,24) print("start running task") print("async task res",res.get() ) return HttpResponse('res %s'%res.get())
五、在django中使用計(jì)劃任務(wù)功能
There's the django-celery-beat extension that stores the schedule in the Django database, and presents a convenientadmin interface to manage periodic tasks at runtime.
To install and use this extension:
1.Use pip to install the package:
$ pip install django-celery-beat
2.Add the django_celery_beat module to INSTALLED_APPS in your Django project' settings.py:
INSTALLED_APPS = ( ..., 'django_celery_beat', )
Note that there is no dash in the module name, only underscores.
3.Apply Django database migrations so that the necessary tables are created:
$ python manage.py migrate
4.Start the celery beat service using the django scheduler:
$ celery -A proj beat -l info -S django
5.Visit the Django-Admin interface to set up some periodic tasks.
在admin頁(yè)面里,有3張表
配置完長(zhǎng)這樣
此時(shí)啟動(dòng)你的celery beat 和worker,會(huì)發(fā)現(xiàn)每隔2分鐘,beat會(huì)發(fā)起一個(gè)任務(wù)消息讓worker執(zhí)行scp_task任務(wù)
注意,經(jīng)測(cè)試,每添加或修改一個(gè)任務(wù),celery beat都需要重啟一次,要不然新的配置不會(huì)被celery beat進(jìn)程讀到
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python測(cè)試開(kāi)發(fā)django之使用supervisord?后臺(tái)啟動(dòng)celery?服務(wù)(worker/beat)
- python中使用Celery容聯(lián)云異步發(fā)送驗(yàn)證碼功能
- Python中celery的使用
- python使用celery實(shí)現(xiàn)訂單超時(shí)取消
- python3中celery異步框架簡(jiǎn)單使用+守護(hù)進(jìn)程方式啟動(dòng)
- Python Celery異步任務(wù)隊(duì)列使用方法解析
- python使用celery實(shí)現(xiàn)異步任務(wù)執(zhí)行的例子
- Python環(huán)境下安裝使用異步任務(wù)隊(duì)列包Celery的基礎(chǔ)教程
- python中celery的基本使用詳情
相關(guān)文章
Python對(duì)象類(lèi)型及其運(yùn)算方法(詳解)
下面小編就為大家?guī)?lái)一篇Python對(duì)象類(lèi)型及其運(yùn)算方法(詳解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07詳解python數(shù)據(jù)結(jié)構(gòu)和算法
這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)和算法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04Python自動(dòng)化測(cè)試PO模型封裝過(guò)程詳解
在 PO 模式中抽離封裝集成一個(gè)BasePage 類(lèi),該基類(lèi)應(yīng)該擁有一個(gè)只實(shí)現(xiàn) webdriver 實(shí)例的屬性,通常情況下PO 模型可以大大提高測(cè)試用例的維護(hù)效率2021-06-06使用Python對(duì)SQLite數(shù)據(jù)庫(kù)操作
本文主要介紹了Python對(duì)SQLite數(shù)據(jù)庫(kù)操作的簡(jiǎn)單教程。SQLite是一種嵌入式數(shù)據(jù)庫(kù),它的數(shù)據(jù)庫(kù)就是一個(gè)文件。由于SQLite本身是C寫(xiě)的,而且體積很小,所以,經(jīng)常被集成到各種應(yīng)用程序中,甚至在IOS和Android的APP中都可以集成。2017-04-04python Multiprocessing.Pool進(jìn)程池模塊詳解
multiprocessing模塊提供了一個(gè)Process類(lèi)來(lái)代表一個(gè)進(jìn)程對(duì)象,multiprocessing模塊像線程一樣管理進(jìn)程,這個(gè)是multiprocessing的核心,它與threading很相似,對(duì)多核CPU的利用率會(huì)比threading好的多2022-10-10TensorFlow神經(jīng)網(wǎng)絡(luò)構(gòu)造線性回歸模型示例教程
這篇文章主要為大家介紹了TensorFlow構(gòu)造線性回歸模型示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11python如何實(shí)現(xiàn)內(nèi)容寫(xiě)在圖片上
這篇文章主要為大家詳細(xì)介紹了python如何實(shí)現(xiàn)內(nèi)容寫(xiě)在圖片上,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03