本节内容
Celery介绍和基本使用
在项目中如何使用celery
启用多个workers
Celery 定时任务
与django结合
通过django配置celery periodic task
一、Celery介绍和基本使用
Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考虑使用celery, 举几个实例场景中可用的例子:
- 你想对100台机器执行一条批量命令,可能会花很长时间 ,但你不想让你的程序等着结果返回,而是给你返回 一个任务ID,你过一段时间只需要拿着这个任务id就可以拿到任务执行结果, 在任务执行ing进行时,你可以继续做其它的事情。
- 你想做一个定时任务,比如每天检测一下你们所有客户的资料,如果发现今天 是客户的生日,就给他发个短信祝福
Celery 在执行任务时需要通过一个消息中间件来接收和发送任务消息,以及存储任务结果, 一般使用rabbitMQ or Redis,后面会讲
1.1 Celery有以下优点:
- 简单:一单熟悉了celery的工作流程后,配置和使用还是比较简单的
- 高可用:当任务执行失败或执行过程中发生连接中断,celery 会自动尝试重新执行任务
- 快速:一个单进程的celery每分钟可处理上百万个任务
- 灵活: 几乎celery的各个组件都可以被扩展及自定制
Celery基本工作流程图
1.2 Celery安装使用
Celery的默认broker是RabbitMQ, 仅需配置一行就可以
1
2 1broker_url = 'amqp://guest:guest@localhost:5672//'
2
rabbitMQ 没装的话请装一下,安装看这里 http://docs.celeryproject.org/en/latest/getting-started/brokers/rabbitmq.html\#id3
使用Redis做broker也可以
安装redis组件
1
2 1$ pip install -U "celery[redis]"
2
配置
Configuration is easy, just configure the location of your Redis database:
1
2
3 1app.conf.broker_url = 'redis://localhost:6379/0'
2
3
Where the URL is in the format of:
1
2
3 1redis://:password@hostname:port/db_number
2
3
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:
1
2
3 1app.conf.result_backend = 'redis://localhost:6379/0'
2
3
1. 3 开始使用Celery啦
安装celery模块
1
2 1$ pip install celery
2
创建一个celery application 用来定义你的任务列表
创建一个任务文件就叫tasks.py吧
1
2
3
4
5
6
7
8
9
10
11
12 1from celery import Celery
2
3app = Celery('tasks',broker='redis://localhost', backend='redis://localhost')
4
5@app.task
6
7def add(x,y):
8
9 print("running...",x,y)
10
11 return x+y
12
启动Celery Worker来开始监听并执行任务
1
2 1$ celery -A tasks worker --loglevel=info
2
调用任务
再打开一个终端, 进行命令行模式,调用任务
1
2
3
4
5
6 1>>> from tasks import add
2
3
4
5>>> add.delay(4, 4)
6
看你的worker终端会显示收到 一个任务,此时你想看任务结果的话,需要在调用 任务时 赋值个变量
1
2 1>>> result = add.delay(4, 4)
2
The ready() method returns whether the task has finished processing or not:
1
2
3
4 1>>> result.ready()
2False
3
4
You can wait for the result to complete, but this is rarely used since it turns the asynchronous call into a synchronous one:
1
2
3
4 1>>> result.get(timeout=1)
28
3
4
In case the task raised an exception, get() will re-raise the exception, but you can override this by specifying the propagate argument:
1
2
3 1>>> result.get(propagate=False)
2
3
If the task raised an exception you can also gain access to the original traceback:
1
2
3 1>>> result.traceback
2…
3
二、在项目中如何使用celery
可以把celery配置成一个应用
目录格式如下
1
2
3
4
5
6
7
8
9
10 1proj/__init__.py
2
3
4
5 /celery.py
6
7
8
9 /tasks.py
10
proj/celery.py内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 1from __future__ import absolute_import, unicode_literals
2from celery import Celery
3app = Celery('proj',
4 broker='amqp://',
5 backend='amqp://',
6 include=['proj.tasks'])
7
8# Optional configuration, see the application user guide.
9
10app.conf.update(
11 result_expires=3600,
12)
13
14if __name__ == '__main__':
15 app.start()
16
proj/tasks.py中的内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 1from __future__ import absolute_import, unicode_literals
2from .celery import app
3
4
5@app.task
6def add(x, y):
7 return x + y
8
9
10@app.task
11def mul(x, y):
12 return x * y
13
14
15@app.task
16def xsum(numbers):
17 return sum(numbers)
18
**启动worker **
1
2 1$ celery -A proj worker -l info
2
输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1-------------- celery@Alexs-MacBook-Pro.local v4.0.2 (latentcall)
2---- **** -----
3--- * *** * -- Darwin-15.6.0-x86_64-i386-64bit 2017-01-26 21:50:24
4-- * - **** ---
5- ** ---------- [config]
6- ** ---------- .> app: proj:0x103a020f0
7- ** ---------- .> transport: redis://localhost:6379//
8- ** ---------- .> results: redis://localhost/
9- *** --- * --- .> concurrency: 8 (prefork)
10-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
11--- ***** -----
12 -------------- [queues]
13 .> celery exchange=celery(direct) key=celery
14
后台启动worker
In the background
在生产中,您需要在后台运行worker,这在daemonization教程中有详细描述(翻译)
In production you’ll want to run the worker in the background, this is described in detail in the daemonization tutorial.
守护程序脚本使用celery multi命令在后台启动一个或多个worker(翻译)
The daemonization scripts uses the celery multi command to start one or more workers in the background:
1
2
3
4
5
6 1$ celery multi start w1 -A proj -l info
2celery multi v4.0.0 (latentcall)
3> Starting nodes...
4 > w1.halcyon.local: OK
5
6
You can restart it too:
1
2
3
4
5
6
7
8
9
10
11
12 1$ celery multi restart w1 -A proj -l info
2celery multi v4.0.0 (latentcall)
3> Stopping nodes...
4 > w1.halcyon.local: TERM -> 64024
5> Waiting for 1 node.....
6 > w1.halcyon.local: OK
7> Restarting node w1.halcyon.local: OK
8celery multi v4.0.0 (latentcall)
9> Stopping nodes...
10 > w1.halcyon.local: TERM -> 64052
11
12
or stop it:
1
2
3 1$ celery multi stop w1 -A proj -l info
2
3
stop命令是异步的,因此它不会等待worker关闭。您可能希望使用stopwait命令,这可确保在退出之前完成所有当前正在执行的任务:(翻译)
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:
1
2 1$ celery multi stopwait w1 -A proj -l info
2
三、Celery 定时任务
celery支持定时任务,设定好任务的执行时间,celery就会定时自动帮你执行, 这个定时任务模块叫celery beat
写一个脚本 叫periodic_task.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 1from celery import Celery
2from celery.schedules import crontab
3
4app = Celery()
5
6@app.on_after_configure.connect
7
8def setup_periodic_tasks(sender, **kwargs):
9 # Calls test('hello') every 10 seconds.
10 sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')
11 # Calls test('world') every 30 seconds
12 sender.add_periodic_task(30.0, test.s('world'), expires=10)
13 # Executes every Monday morning at 7:30 a.m.
14 sender.add_periodic_task(
15 crontab(hour=7, minute=30, day_of_week=1),
16 test.s('Happy Mondays!'),
17 )
18
19@app.task
20def test(arg):
21 print(arg)
22
add_periodic_task 会添加一条定时任务
上面是通过调用函数添加定时任务,也可以像写配置文件 一样的形式添加, 下面是每30s执行的任务
1
2
3
4
5
6
7
8
9 1app.conf.beat_schedule = {
2 'add-every-30-seconds': {
3 'task': 'tasks.add',
4 'schedule': 30.0,
5 'args': (16, 16)
6 },
7}
8app.conf.timezone = 'UTC'
9
任务添加好了,需要让celery单独启动一个进程来定时发起这些任务, 注意, 这里是发起任务,不是执行,这个进程只会不断的去检查你的任务计划, 每发现有任务需要执行了,就发起一个任务调用消息,交给celery worker去执行
启动任务调度器 celery beat
1
2 1$ celery -A periodic_task beat
2
输出like below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 1celery beat v4.0.2 (latentcall) is starting.
2__ - ... __ - _
3
4LocalTime -> 2017-02-08 18:39:31
5
6Configuration ->
7
8 . broker -> redis://localhost:6379//
9 . loader -> celery.loaders.app.AppLoader
10 . scheduler -> celery.beat.PersistentScheduler
11 . db -> celerybeat-schedule
12
13 . logfile -> [stderr]@%WARNING
14
15 . maxinterval -> 5.00 minutes (300s)
16
此时还差一步,就是还需要启动一个worker,负责执行celery beat发起的任务
启动celery worker来执行任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1$ celery -A periodic_task worker
2
3 -------------- celery@Alexs-MacBook-Pro.local v4.0.2 (latentcall)
4---- **** -----
5--- * *** * -- Darwin-15.6.0-x86_64-i386-64bit 2017-02-08 18:42:08
6
7-- * - **** ---
8
9- ** ---------- [config]
10- ** ---------- .> app: tasks:0x104d420b8
11
12- ** ---------- .> transport: redis://localhost:6379//
13- ** ---------- .> results: redis://localhost/
14- *** --- * --- .> concurrency: 8 (prefork)
15-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
16--- ***** -----
17 -------------- [queues]
18 .> celery exchange=celery(direct) key=celery
19
好啦,此时观察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:
1
2 1$ celery -A periodic_task beat -s /home/celery/var/run/celerybeat-schedule
2
更复杂的定时配置
上面的定时任务比较简单,只是每多少s执行一个任务,但如果你想要每周一三五的早上8点给你发邮件怎么办呢?哈,其实也简单,用crontab功能,跟linux自带的crontab功能是一样的,可以个性化定制任务执行时间
1
2
3
4
5
6
7
8
9
10
11
12
13 1from celery.schedules import crontab
2
3
4app.conf.beat_schedule = {
5 # Executes every Monday morning at 7:30 a.m.
6 'add-every-monday-morning': {
7 'task': 'tasks.add',
8 'schedule': crontab(hour=7, minute=30, day_of_week=1),
9 'args': (16, 16),
10 },
11
12}
13
上面的这条意思是每周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. |
crontab(minute=0, hour='0,3,6,9,12,15,18,21') | Same as previous. |
crontab(minute='*/15') | Execute every 15 minutes. |
crontab(day_of_week='sunday') | Execute every minute (!) at Sundays. |
crontab(minute='', hour='',day_of_week='sun') | Same as previous. |
crontab(minute='*/10', hour='3,17,22',day_of_week='thu,fri') | 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. |
crontab(0, 0, day_of_month='2-30/3') | Execute on every even numbered day. |
crontab(0, 0, day_of_month='1-7,15-21') | Execute on the first and third weeks of the month. |
crontab(0, 0,day_of_month='11', month_of_year='5') | Execute on the eleventh of May every year. |
crontab(0, 0, month_of_year='*/3') | Execute on the first month of every quarter. |
1 | 1 |
上面能满足你绝大多数定时任务需求了,甚至还能根据潮起潮落来配置定时任务, 具体看 http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html\#solar-schedules
四、最佳实践之与django结合
django 可以轻松跟celery结合实现异步任务,只需简单配置即可(翻译)
If you have a modern Django project layout like:
1
2
3
4
5
6
7 1- proj/
2 - proj/__init__.py
3 - proj/settings.py
4 - proj/urls.py
5- manage.py
6
7
then the recommended way is to create a new
proj/proj/celery.py module that defines the Celery instance:
file: *proj/proj/celery.py *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 1from __future__ import absolute_import, unicode_literals
2
3
4
5import os
6
7
8
9from celery import Celery
10
11
12
13
14
15
16
17# set the default Django settings module for the 'celery' program.
18
19
20
21os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
22
23app = Celery('proj')
24
25# Using a string here means the worker don't have to serialize
26
27
28
29# the configuration object to child processes.
30
31# - namespace='CELERY' means all celery-related configuration keys
32
33# should have a `CELERY_` prefix.
34
35app.config_from_object('django.conf:settings', namespace='CELERY')
36
37# Load task modules from all registered Django app configs.
38
39app.autodiscover_tasks()
40
41
42@app.task(bind=True)
43def debug_task(self):
44
45 print('Request: {0!r}'.format(self.request))
46
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:
1
2
3
4
5
6
7
8 1from __future__ import absolute_import, unicode_literals
2
3# This will make sure the app is always imported when
4
5# Django starts so that shared_task will use this app.
6from .celery import app as celery_app
7__all__ = ['celery_app']
8
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:
1
2 1from __future__ import absolute_import
2
Then we set the default
DJANGO_SETTINGS_MODULE environment variable for the celery command-line program:
1
2 1os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
2
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:
1
2 1app = Celery('proj')
2
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
1 | 1` |
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.
1
2 1app.config_from_object('django.conf:settings', namespace='CELERY')
2
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:
1
2 1app.autodiscover_tasks()
2
With the line above Celery will automatically discover tasks from all of your installed apps, following the tasks.py convention:
1
2
3
4
5
6
7 1- app1/
2 - tasks.py
3 - models.py
4- app2/
5 - tasks.py
6 - models.py
7
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里写你的任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1# Create your tasks here
2from __future__ import absolute_import, unicode_literals
3
4from celery import shared_task
5
6@shared_task
7
8def add(x, y):
9 return x + y
10
11
12@shared_task
13
14def mul(x, y):
15 return x * y
16
17
18@shared_task
19
20
21def xsum(numbers):
22 return sum(numbers)
23
在你的django views里调用celery task
1
2
3
4
5
6
7
8
9
10
11
12 1from django.shortcuts import render,HttpResponse
2# Create your views here.
3
4from bernard import tasks
5
6def task_test(request):
7
8 res = tasks.add.delay(228,24)
9 print("start running task")
10 print("async task res",res.get() )
11 return HttpResponse('res %s'%res.get())
12
五、在django中使用计划任务功能
有一个django-celery-beat扩展,它将日程表存储在Django数据库中,并提供了一个方便的管理界面来管理运行时的周期性任务(翻译)
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:
1
2
3 1$ pip install django-celery-beat
2
3
Add the django_celery_beat module to INSTALLED_APPS in your Django project’ settings.py:
1
2
3
4
5
6
7
8 1 INSTALLED_APPS = (
2 ...,
3 'django_celery_beat',
4 )
5
6Note that there is no dash in the module name, only underscores.
7
8
Apply Django database migrations so that the necessary tables are created:
1
2
3 1$ python manage.py migrate
2
3
Start the celery beat service using the django scheduler:
1
2
3 1$ celery -A proj beat -l info -S django
2
3
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进程读到