Celery介紹和基本使用html
在項目中如何使用celerynode
啓用多個workerspython
Celery 定時任務linux
與django結合redis
經過django配置celery periodic taskdjango
Celery 是一個 基於python開發的分佈式異步消息任務隊列,經過它能夠輕鬆的實現任務的異步處理, 若是你的業務場景中須要用到異步任務,就能夠考慮使用celery, 舉幾個實例場景中可用的例子:app
Celery 在執行任務時須要經過一個消息中間件來接收和發送任務消息,以及存儲任務結果, 通常使用rabbitMQ or Redis,後面會講dom
1.1 Celery有如下優勢:異步
Celery基本工做流程圖async
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]"
python鏈接的redis組件
pip3 install 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吧 'redis://:123456@192.168.31.128:6379/0'
#!/usr/bin/env python # -*- coding:utf-8 -*- from celery import Celery app = Celery('tasks', broker='redis://:123456@192.168.31.128', backend='redis://:123456@192.168.31.128') #拿到結果把結果寫到某個地方 @app.task def add(x, y): #這是worker能夠執行的一個任務 print("running...", x, y) return x + y @app.task def cmd(cmd_str): print("running cmd",cmd_str)
啓動Celery Worker來開始監聽並執行任務
$ celery -A tasks worker --loglevel=info $ celery -A celery_test worker -l debug
全部任務
[tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . celery_test.add *** . celery_test.cmd ***
調用任務
再打開一個終端, 進行命令行模式,調用任務
>>> from tasks import add >>> add.delay(4, 4)
看你的worker終端會顯示收到 一個任務,此時你想看任務結果的話,須要在調用 任務時 賦值個變量
>>> result = add.delay(4, 4)
>>> add.delay(45,8) #發送任務 <AsyncResult: 73f83dce-61e7-48c7-816a-802c9516b014> >>> t1=add.delay(45,3) 賦值給t1 >>> t1 #拿到的是一個實例 <AsyncResult: ff47acc1-99b5-4b41-8744-3368af3e27e0> >>> t1.get() #實例.get()拿到結果 48
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 #拿到錯誤結果 …
2、在項目中如何使用celery
能夠把celery配置成一個應用
目錄格式以下
proj/__init__.py /celery.py /tasks.py
proj/celery.py內容
from __future__ import absolute_import, unicode_literals #從python的絕對路徑導入而不是當前的腳本 #在python2和python3作兼容支持的 from celery import Celery app = Celery('proj',#app的名字 broker='redis://:123456@192.168.31.128',#連rabbitmq或redis backend='redis://:123456@192.168.31.128', include=['s3proj.tasks','s3proj.tasks2']) # Optional configuration, see the application user guide. app.conf.update(#給app設置參數 result_expires=3600,#保存時間爲1小時 ) if __name__ == '__main__': app.start()
proj/tasks.py中的內容
from __future__ import absolute_import, unicode_literals #從python的絕對路徑導入而不是當前的腳本 #在python2和python3作兼容支持的 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) #################################### from __future__ import absolute_import, unicode_literals #從python的絕對路徑導入而不是當前的腳本 #在python2和python3作兼容支持的 from .celery import app @app.task def cmd(cmd): print("running cmd",cmd) @app.task def file_transfer(filename): print("sending file",filename)
啓動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
後臺啓動worker
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,能夠同時開啓多個celery
[root@wenwen szw]# celery multi start w1 -A s3proj -l info celery multi v4.0.2 (latentcall) > Starting nodes... > w1@wenwen.localdomain: OK
You can restart it too:
重啓celery
$ 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
[root@wenwen szw]# celery multi stop w1 #殺掉celery進程 celery multi v4.0.2 (latentcall) > Stopping nodes... > w1@wenwen.localdomain: TERM -> 39496
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支持定時任務,設定好任務的執行時間,celery就會定時自動幫你執行, 這個定時任務模塊叫celery beat
from __future__ import absolute_import, unicode_literals #從python的絕對路徑導入而不是當前的腳本 #在python2和python3作兼容支持的 from celery.schedules import crontab from .celery import app @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs):#用sender添加任務 # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') #每隔10秒執行一次task函數 .s是傳的參數 #任務名 # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) #任務結果保存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("run func:",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 beat
$ celery -A periodic_task beat $ celery -A s3proj.periodic_tasks beat -l debug #啓動定時任務,必須指定哪一個文件啓動定時任務
輸出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)
此時還差一步,就是還須要啓動一個worker,負責執行celery beat發起的任務
啓動celery worker來執行任務
$ 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
好啦,此時觀察worker的輸出,是否是每隔一小會,就會執行一次定時任務呢!
注意: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
上面的定時任務比較簡單,只是每多少s執行一個任務,但若是你想要每週一三五的早上8點給你發郵件怎麼辦呢?哈,其實也簡單,用crontab功能,跟linux自帶的crontab功能是同樣的,能夠個性化定製任務執行時間
linux crontab http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
from celery.schedules import crontab app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-monday-morning': { 'task': 's3proj.tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, }
上面的這條意思是每週1的早上7.30執行tasks.add任務
還有更多定時配置方式以下:
上面的這條意思是每週1的早上7.30執行tasks.add任務
還有更多定時配置方式以下:
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
django 能夠輕鬆跟celery結合實現異步任務,只需簡單配置便可
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 寫了一個這個就把selery的配置寫好了
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', 'PerfectCRM.settings')#配置環境變量 app = Celery('celery_task') # 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') #你能夠把celery鏈接的RabbitMQ存到settings但你必須按他規定的格式,必須CELERY大寫開頭 # Load task modules from all registered Django app configs. app.autodiscover_tasks() #app下自動發現selery #可以找到全部app下的selery任務 @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
: #找這個項目下全部app
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'] #找這個全部項目下的全部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', 'PerfectCRM.settings')
#項目名.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('celery_task')
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')
#你能夠把celery鏈接的RabbitMQ存到settings但你必須按他規定的格式,必須CELERY大寫開頭
Next, a common practice for reusable apps is to define all tasks in a separate tasks.py
module, and Celery does have a way to auto-discover these modules:
app.autodiscover_tasks()
#無論你在那個app裏建立clelry任務,他都能自動發現,就像djangoadmin同樣能自動發現
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文件,必須叫這個名字
而後在具體的app裏的tasks.py裏寫你的任務
from __future__ import absolute_import, unicode_literals from celery import shared_task #在這個app裏的任務和其餘app裏的任務是能夠互相共享d @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)
進到項目裏面啓動 worker
celery -A PerfectCRM worker -l debug
進到項目裏面啓動項目
python3 manage.py runserver 0.0.0.0:9000
settings裏配置
CELERY_BROKER_URL="redis://localhost" CELERY_RESULT_BACKEND="redis://localhost"
在你的django views裏調用celery task
from crm.tasks import add,mul #導入worker from celery.result import AsyncResult # Create your views here. def celery_test(request): """ 掉一個視圖,把任務交給celery,並返回任務id :param request: :return: """ task=add.delay(4,42) # res=task.get() # return HttpResponse(res)#返回的是任務結果 return HttpResponse(task.id)#返回的是任務id def celery_res(request): """ 經過任務id取出任務結果 :param request: :return: """ task_id="686c19f5-89d1-4c57-8e91-669f9e2716e5" res=AsyncResult(id=task_id) return HttpResponse(res.get())
There’s the django-celery-beat extension that stores the schedule in the Django database, and presents a convenient admin interface to manage periodic tasks at runtime.
To install and use this extension:
Use pip to install the package: 安裝定時任務要裝的插件
$ pip install django-celery-beat
Add the django_celery_beat
module to INSTALLED_APPS
in your Django project’ settings.py
: #settings裏須要配置
INSTALLED_APPS = ( ..., 'django_celery_beat', )
Note that there is no dash in the module name, only underscores.
Apply Django database migrations so that the necessary tables are created:
由於須要建立幾張表
$ python manage.py migrate
Start the celery beat service using the django
scheduler:
#從django裏面讀數據要加 -S django 不加的話不會報錯也不會從django裏面讀數據
$ celery -A proj beat -l info -S django
Visit the Django-Admin interface to set up some periodic tasks.
在admin頁面裏,有3張表
多長時間
每隔多長時間
配置完長這樣
此時啓動你的celery beat 和worker,會發現每隔2分鐘,beat會發起一個任務消息讓worker執行scp_task任務
注意,經測試,每添加或修改一個任務,celery beat都須要重啓一次,要否則新的配置不會被celery beat進程讀到