一、Celery介绍
1. Celery是什么
Celery是一个强大的分布式任务队列,它可以让任务的执行完全脱离主程序,甚至可以被分配到其他主机上运行。
2.主要组建
Task
具体要做的事情
Broker
经纪人
数据结构中的队列
Worker
消费者
实际执行任务
Beat
定时任务调度器
配置定时任务发送给Broker
Backend
保存任务执行结果
关系结构
framework.png
二、Celery入门使用
1. 环境准备
a) centos7上安装redis
redis-server # 检查是否已经安装redis
sudo yum -y install redis
sudo systemctl start redis
[root@VM_249_182_centos ~]# redis-server
-bash: redis-server: command not found
[root@VM_249_182_centos ~]# sudo yum -y install redis
Loaded plugins: fastestmirror, langpacks
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
docker-ce-stable | 3.5 kB 00:00:00
epel | 5.4 kB 00:00:00
extras | 3.4 kB 00:00:00
os | 3.6 kB 00:00:00
updates | 3.4 kB 00:00:00
(1/5): extras/7/x86_64/primary_db | 205 kB 00:00:00
(2/5): epel/7/x86_64/updateinfo | 993 kB 00:00:00
(3/5): updates/7/x86_64/primary_db | 6.5 MB 00:00:00
(4/5): epel/7/x86_64/primary_db | 6.8 MB 00:00:00
(5/5): docker-ce-stable/x86_64/primary_db | 31 kB 00:00:00
Determining fastest mirrors
Resolving Dependencies
--> Running transaction check
---> Package redis.x86_64 0:3.2.12-2.el7 will be installed
--> Processing Dependency: libjemalloc.so.1()(64bit) for package: redis-3.2.12-2.el7.x86_64
--> Running transaction check
---> Package jemalloc.x86_64 0:3.6.0-1.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
==================================================================================================================================================================================================================
Package Arch Version Repository Size
==================================================================================================================================================================================================================
Installing:
redis x86_64 3.2.12-2.el7 epel 544 k
Installing for dependencies:
jemalloc x86_64 3.6.0-1.el7 epel 105 k
Transaction Summary
==================================================================================================================================================================================================================
Install 1 Package (+1 Dependent package)
Total download size: 648 k
Installed size: 1.7 M
Downloading packages:
(1/2): jemalloc-3.6.0-1.el7.x86_64.rpm | 105 kB 00:00:00
(2/2): redis-3.2.12-2.el7.x86_64.rpm | 544 kB 00:00:00
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total 3.1 MB/s | 648 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : jemalloc-3.6.0-1.el7.x86_64 1/2
Installing : redis-3.2.12-2.el7.x86_64 2/2
Verifying : redis-3.2.12-2.el7.x86_64 1/2
Verifying : jemalloc-3.6.0-1.el7.x86_64 2/2
Installed:
redis.x86_64 0:3.2.12-2.el7
Dependency Installed:
jemalloc.x86_64 0:3.6.0-1.el7
Complete!
[root@VM_249_182_centos ~]# sudo systemctl start redis
[root@VM_249_182_centos ~]# vi /etc/redis.conf
[root@VM_249_182_centos ~]# sudo systemctl restart redis
b) centos7上安装celery及相关依赖
pip install 'celery[redis]'
2. 使用celery编写demo
a) 创建Celery实例
将下面的代码保存为文件 tasks.py
# -*- coding: utf-8 -*-
import time
from celery import Celery
broker = 'redis://127.0.0.1:6379'
backend = 'redis://127.0.0.1:6379/0'
app = Celery('my_task', broker=broker, backend=backend)
@app.task
def add(x, y):
time.sleep(5) # 模拟耗时操作
return x + y
【说明】
- 创建了一个 Celery 实例 app,名称为 my_task;
- 指定消息中间件用 redis,URL 为 redis://127.0.0.1:6379;
- 指定存储用 redis,URL 为 redis://127.0.0.1:6379/0;
- 创建了一个 Celery 任务 add,当函数被 @app.task 装饰后,就成为可被 Celery 调度的任务;
b) 启动 Celery Worker
在当前目录,使用如下方式启动 Celery Worker
celery worker -A tasks --loglevel=info
【说明】
- 参数 -A 指定了 Celery 实例的位置,本例是在 tasks.py 中,Celery 会自动在该文件中寻找 Celery 对象实例,当然,我们也可以自己指定,在本例,使用 -A tasks.app;
- 参数 --loglevel 指定了日志级别,默认为 warning,也可以使用 -l info 来表示;
- 若未成功启动redis则会报错,显示如下:
[root@VM_249_182_centos celery]# celery worker -A tasks --loglevel=info
/root/.pyenv/versions/3.7.3/lib/python3.7/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!
Please specify a different user using the --uid option.
User information: uid=0 euid=0 gid=0 egid=0
uid=uid, euid=euid, gid=gid, egid=egid,
-------------- celery@VM_249_182_centos v4.3.0 (rhubarb)
---- **** -----
--- * *** * -- Linux-3.10.0-514.21.1.el7.x86_64-x86_64-with-centos-7.3.1611-Core 2019-07-25 10:56:19
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: my_task:0x7f0227d62e10
- ** ---------- .> transport: redis://127.0.0.1:6379//
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. tasks.add
[2019-07-25 10:56:19,334: ERROR/MainProcess] consumer: Cannot connect to redis://127.0.0.1:6379//: Error 111 connecting to 127.0.0.1:6379. Connection refused..
Trying again in 2.00 seconds...
[2019-07-25 10:56:21,338: ERROR/MainProcess] consumer: Cannot connect to redis://127.0.0.1:6379//: Error 111 connecting to 127.0.0.1:6379. Connection refused..
Trying again in 4.00 seconds...
- 若成功启动redis,则显示如下:
[root@VM_249_182_centos celery]# celery worker -A tasks --loglevel=info
/root/.pyenv/versions/3.7.3/lib/python3.7/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!
Please specify a different user using the --uid option.
User information: uid=0 euid=0 gid=0 egid=0
uid=uid, euid=euid, gid=gid, egid=egid,
-------------- celery@VM_249_182_centos v4.3.0 (rhubarb)
---- **** -----
--- * *** * -- Linux-3.10.0-514.21.1.el7.x86_64-x86_64-with-centos-7.3.1611-Core 2019-07-25 11:01:46
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: my_task:0x7f9f12a6a320
- ** ---------- .> transport: redis://127.0.0.1:6379//
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. tasks.add
[2019-07-25 11:01:46,070: INFO/MainProcess] Connected to redis://127.0.0.1:6379//
[2019-07-25 11:01:46,078: INFO/MainProcess] mingle: searching for neighbors
[2019-07-25 11:01:47,095: INFO/MainProcess] mingle: all alone
[2019-07-25 11:01:47,106: INFO/MainProcess] celery@VM_249_182_centos ready.
c) 调用任务(通过命令行)
现在,我们可以在应用程序中使用 delay() 或 apply_async() 方法来调用任务。
在当前目录打开 Python 控制台,输入以下代码:
[root@VM_249_182_centos celery]# python
Python 3.7.3 (default, Apr 10 2019, 16:42:27)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more informati
>>> from tasks import add
>>> add.delay(2, 8)
<AsyncResult: 00d23986-beec-4f0e-a7ae-6ccd537418ba>
在上面,我们从 tasks.py 文件中导入了 add 任务对象,然后使用 delay() 方法将任务发送到消息中间件(Broker),Celery Worker 进程监控到该任务后,就会进行执行。我们将窗口切换到 Worker 的启动窗口,会看到多了两条日志:
[2019-07-25 11:01:47,106: INFO/MainProcess] celery@VM_249_182_centos ready.
[2019-07-25 11:16:26,890: INFO/MainProcess] Received task: tasks.add[00d23986-beec-4f0e-a7ae-6ccd537418ba]
[2019-07-25 11:16:31,902: INFO/ForkPoolWorker-1] Task tasks.add[00d23986-beec-4f0e-a7ae-6ccd537418ba] succeeded in 5.010160811245441s: 10
这说明任务已经被调度并执行成功。
另外,我们如果想获取执行后的结果,可以这样做:
>>> result = add.delay(2, 6)
>>> result.ready()
True
>>> result.get()
8
>>>
d) 调用任务(通过应用程序)
在上面,我们是在 Python 的环境中调用任务。事实上,我们通常在应用程序中调用任务。比如,将下面的代码保存为 client.py:
# -*- coding: utf-8 -*-
from tasks import add
# 异步任务
add.delay(2, 8)
print('hello world')
运行命令 $ python client.py,可以看到,虽然任务函数 add 需要等待 5 秒才返回执行结果,但由于它是一个异步任务,不会阻塞当前的主程序,因此主程序会往下执行 print 语句,打印出结果。
二、Celery配置使用
在上面的例子中,我们直接把 Broker 和 Backend 的配置写在了程序当中,更好的做法是将配置项统一写入到一个配置文件中,通常我们将该文件命名为 celeryconfig.py
。Celery 的配置比较多,可以在官方文档查询每个配置项的含义。
下面,我们再看一个例子。项目结构如下:
celery_demo # 项目根目录
├── celery_app # 存放 celery 相关文件
│ ├── __init__.py
│ ├── celeryconfig.py # 配置文件
│ ├── task1.py # 任务文件 1
│ └── task2.py # 任务文件 2
└── client.py # 应用程序
1. init.py 代码如下:
# -*- coding: utf-8 -*-
from celery import Celery
app = Celery('demo') # 创建 Celery 实例
app.config_from_object('celery_app.celeryconfig') # 通过 Celery 实例加载配置模块
2. celeryconfig.py 代码如下:
BROKER_URL = 'redis://127.0.0.1:6379' # 指定 Broker
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # 指定 Backend
CELERY_TIMEZONE='Asia/Shanghai' # 指定时区,默认是 UTC
# CELERY_TIMEZONE='UTC'
CELERY_IMPORTS = ( # 指定导入的任务模块
'celery_app.task1',
'celery_app.task2'
)
3. task1.py 代码如下:
import time
from celery_app import app
@app.task
def add(x, y):
time.sleep(2)
return x + y
4. task2.py 代码如下:
import time
from celery_app import app
@app.task
def multiply(x, y):
time.sleep(2)
return x * y
5. client.py 代码如下:
# -*- coding: utf-8 -*-
from celery_app import task1
from celery_app import task2
task1.add.apply_async(args=[2, 8]) # 也可用 task1.add.delay(2, 8)
task2.multiply.apply_async(args=[3, 7]) # 也可用 task2.multiply.delay(3, 7)
print 'hello world'
6. 运行代码
现在,让我们启动 Celery Worker 进程,在项目的根目录下执行下面命令:
celery -A celery_app worker --loglevel=info
接着,运行 $ python client.py,它会发送两个异步任务到 Broker,在 Worker 的窗口我们可以看到如下输出
[2019-07-25 11:50:57,532: INFO/MainProcess] celery@VM_249_182_centos ready.
[2019-07-25 11:51:37,852: INFO/MainProcess] Received task: celery_app.task1.add[c33e869d-8531-43fd-9b55-e42f9c0da2b5]
[2019-07-25 11:51:37,876: INFO/MainProcess] Received task: celery_app.task2.multiply[5c449cff-90a0-40e4-885a-6d9c95f3b9af]
[2019-07-25 11:51:39,860: INFO/ForkPoolWorker-1] Task celery_app.task1.add[c33e869d-8531-43fd-9b55-e42f9c0da2b5] succeeded in 2.0075164064764977s: 10
[2019-07-25 11:51:41,864: INFO/ForkPoolWorker-1] Task celery_app.task2.multiply[5c449cff-90a0-40e4-885a-6d9c95f3b9af] succeeded in 2.0028325598686934s: 21
7. delay 和 apply_async 说明
在前面的例子中,我们使用 delay() 或 apply_async() 方法来调用任务。事实上,delay 方法封装了 apply_async,如下:
def delay(self, *partial_args, **partial_kwargs):
"""Shortcut to :meth:`apply_async` using star arguments."""
return self.apply_async(partial_args, partial_kwargs)
也就是说,delay 是使用 apply_async 的快捷方式。apply_async 支持更多的参数,它的一般形式如下:
apply_async(args=(), kwargs={}, route_name=None, **options)
apply_async 常用的参数如下:
- countdown:指定多少秒后执行任务
task1.apply_async(args=(2, 3), countdown=5) # 5 秒后执行任务
- eta (estimated time of arrival):指定任务被调度的具体时间,参数类型是 datetime
from datetime import datetime, timedelta
# 当前 UTC 时间再加 10 秒后执行任务
task1.multiply.apply_async(args=[3, 7], eta=datetime.utcnow() + timedelta(seconds=10))
- expires:任务过期时间,参数类型可以是 int,也可以是 datetime
task1.multiply.apply_async(args=[3, 7], expires=10) # 10 秒后过期
更多的参数列表可以在官方文档中查看。
四、定时任务
Celery 除了可以执行异步任务,也支持执行周期性任务(Periodic Tasks),或者说定时任务。Celery Beat 进程通过读取配置文件的内容,周期性地将定时任务发往任务队列。
让我们看看例子,项目结构如下:
celery_demo # 项目根目录
├── celery_app # 存放 celery 相关文件
├── __init__.py
├── celeryconfig.py # 配置文件
├── task1.py # 任务文件
└── task2.py # 任务文件
在上面工程的基础上(init.py、task1.py、task2.py 均不变) ,修改celeryconfig.py
2. celeryconfig.py 代码如下
# -*- coding: utf-8 -*-
from datetime import timedelta
from celery.schedules import crontab
# Broker and Backend
BROKER_URL = 'redis://127.0.0.1:6379'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
# Timezone
CELERY_TIMEZONE='Asia/Shanghai' # 指定时区,不指定默认为 'UTC'
# CELERY_TIMEZONE='UTC'
# import
CELERY_IMPORTS = (
'celery_app.task1',
'celery_app.task2'
)
# schedules
CELERYBEAT_SCHEDULE = {
'add-every-30-seconds': {
'task': 'celery_app.task1.add',
'schedule': timedelta(seconds=30), # 每 30 秒执行一次
'args': (5, 8) # 任务函数参数
},
'multiply-at-some-time': {
'task': 'celery_app.task2.multiply',
'schedule': crontab(hour=9, minute=50), # 每天早上 9 点 50 分执行一次
'args': (3, 7) # 任务函数参数
}
}
3. 运行代码
a) 两步启动
- 现在,让我们启动 Celery Worker 进程,在项目的根目录下执行下面命令:
celery -A celery_app worker --loglevel=info
启动后展示:
celery -A celery_app worker --loglevel=info
/root/.pyenv/versions/3.7.3/lib/python3.7/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!
Please specify a different user using the --uid option.
User information: uid=0 euid=0 gid=0 egid=0
uid=uid, euid=euid, gid=gid, egid=egid,
-------------- celery@VM_249_182_centos v4.3.0 (rhubarb)
---- **** -----
--- * *** * -- Linux-3.10.0-514.21.1.el7.x86_64-x86_64-with-centos-7.3.1611-Core 2019-07-25 12:04:43
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: demo:0x7fa32430a160
- ** ---------- .> transport: redis://127.0.0.1:6379//
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. celery_app.task1.add
. celery_app.task2.multiply
[2019-07-25 12:04:43,908: INFO/MainProcess] Connected to redis://127.0.0.1:6379//
[2019-07-25 12:04:43,916: INFO/MainProcess] mingle: searching for neighbors
[2019-07-25 12:04:44,932: INFO/MainProcess] mingle: all alone
[2019-07-25 12:04:44,938: INFO/MainProcess] celery@VM_249_182_centos ready.
- 接着,启动 Celery Beat 进程,定时将任务发送到 Broker,在项目根目录下执行下面命令:
celery beat -A celery_app
启动成功后展示
[root@VM_249_182_centos celery_demo]# celery beat -A celery_app
celery beat v4.3.0 (rhubarb) is starting.
__ - ... __ - _
LocalTime -> 2019-07-25 12:05:00
Configuration ->
. broker -> redis://127.0.0.1:6379//
. loader -> celery.loaders.app.AppLoader
. scheduler -> celery.beat.PersistentScheduler
. db -> celerybeat-schedule
. logfile -> [stderr]@%WARNING
. maxinterval -> 5.00 minutes (300s)
之后,在 Worker 窗口我们可以看到,任务 task1 每 30 秒执行一次,而 task2 每天早上 9 点 50 分执行一次。
worker中展示task执行状态如下
[2019-07-25 12:04:44,932: INFO/MainProcess] mingle: all alone
[2019-07-25 12:04:44,938: INFO/MainProcess] celery@VM_249_182_centos ready.
[2019-07-25 12:05:30,204: INFO/MainProcess] Received task: celery_app.task1.add[b69f9798-d6eb-4f6f-a85f-714cc9b47137]
[2019-07-25 12:05:32,211: INFO/ForkPoolWorker-1] Task celery_app.task1.add[b69f9798-d6eb-4f6f-a85f-714cc9b47137] succeeded in 2.0059445835649967s: 13
[2019-07-25 12:06:00,194: INFO/MainProcess] Received task: celery_app.task1.add[bf904b45-4dc3-45d4-b7a9-71151d01d846]
[2019-07-25 12:06:02,202: INFO/ForkPoolWorker-1] Task celery_app.task1.add[bf904b45-4dc3-45d4-b7a9-71151d01d846] succeeded in 2.006621953099966s: 13
[2019-07-25 12:06:30,210: INFO/MainProcess] Received task: celery_app.task1.add[ebcfadcf-1abb-4f47-8266-684483190ed6]
[2019-07-25 12:06:32,213: INFO/ForkPoolWorker-1] Task celery_app.task1.add[ebcfadcf-1abb-4f47-8266-684483190ed6] succeeded in 2.002971686422825s: 13
[2019-07-25 12:07:00,229: INFO/MainProcess] Received task: celery_app.task1.add[34f072f0-64a2-4b84-87a6-3db7ae4eb1b5]
[2019-07-25 12:07:02,240: INFO/ForkPoolWorker-1] Task celery_app.task1.add[34f072f0-64a2-4b84-87a6-3db7ae4eb1b5] succeeded in 2.009701631963253s: 13
[2019-07-25 12:07:30,242: INFO/MainProcess] Received task: celery_app.task1.add[ef3abe5e-85ba-4b07-9abd-acfafb98b29b]
[2019-07-25 12:07:32,244: INFO/ForkPoolWorker-1] Task celery_app.task1.add[ef3abe5e-85ba-4b07-9abd-acfafb98b29b] succeeded in 2.000968459993601s: 13
[2019-07-25 12:08:00,262: INFO/MainProcess] Received task: celery_app.task1.add[5ec429ad-0f94-46c0-a3cd-e5e2881b1af6]
[2019-07-25 12:08:02,270: INFO/ForkPoolWorker-1] Task celery_app.task1.add[5ec429ad-0f94-46c0-a3cd-e5e2881b1af6] succeeded in 2.0074013955891132s: 13
[2019-07-25 12:08:30,279: INFO/MainProcess] Received task: celery_app.task1.add[40faa2bc-93c1-4a27-a0d0-eb53551d21de]
[2019-07-25 12:08:32,283: INFO/ForkPoolWorker-1] Task celery_app.task1.add[40faa2bc-93c1-4a27-a0d0-eb53551d21de] succeeded in 2.003139404579997s: 13
[2019-07-25 12:09:00,294: INFO/MainProcess] Received task: celery_app.task1.add[29980115-ef41-4ff5-abbb-01b46c2501ed]
[2019-07-25 12:09:02,297: INFO/ForkPoolWorker-1] Task celery_app.task1.add[29980115-ef41-4ff5-abbb-01b46c2501ed] succeeded in 2.0018866565078497s: 13
[2019-07-25 12:09:30,304: INFO/MainProcess] Received task: celery_app.task1.add[7ec132f6-81f8-4cb3-ba73-baedd57e4102]
[2019-07-25 12:09:32,306: INFO/ForkPoolWorker-1] Task celery_app.task1.add[7ec132f6-81f8-4cb3-ba73-baedd57e4102] succeeded in 2.0014469530433416s: 13
b) 一个命令执行
celery -B -A celery_app worker --loglevel=info
运行成功后展示如下:
[root@VM_249_182_centos celery_demo]# celery -B -A celery_app worker --loglevel=info
/root/.pyenv/versions/3.7.3/lib/python3.7/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!
Please specify a different user using the --uid option.
User information: uid=0 euid=0 gid=0 egid=0
uid=uid, euid=euid, gid=gid, egid=egid,
-------------- celery@VM_249_182_centos v4.3.0 (rhubarb)
---- **** -----
--- * *** * -- Linux-3.10.0-514.21.1.el7.x86_64-x86_64-with-centos-7.3.1611-Core 2019-07-25 12:12:44
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: demo:0x7f990f36a198
- ** ---------- .> transport: redis://127.0.0.1:6379//
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. celery_app.task1.add
. celery_app.task2.multiply
[2019-07-25 12:12:44,120: INFO/MainProcess] Connected to redis://127.0.0.1:6379//
[2019-07-25 12:12:44,155: INFO/MainProcess] mingle: searching for neighbors
[2019-07-25 12:12:44,293: INFO/Beat] beat: Starting...
[2019-07-25 12:12:44,311: INFO/Beat] Scheduler: Sending due task add-every-30-seconds (celery_app.task1.add)
[2019-07-25 12:12:45,242: INFO/MainProcess] mingle: all alone
[2019-07-25 12:12:45,249: INFO/MainProcess] celery@VM_249_182_centos ready.
[2019-07-25 12:12:45,625: INFO/MainProcess] Received task: celery_app.task1.add[3db6014f-d76e-425c-9ad7-e20d39a1d50c]
[2019-07-25 12:12:47,632: INFO/ForkPoolWorker-2] Task celery_app.task1.add[3db6014f-d76e-425c-9ad7-e20d39a1d50c] succeeded in 2.0060395151376724s: 13
五、参考连接
http://funhacks.net/2016/12/13/celery/
https://celery.readthedocs.io/en/latest/userguide/tasks.html#tips-and-best-practices
https://devchecklists.com/celery-tasks-checklist/
网友评论