celery多任务定时
简单的项目目录结构如下:
/root/test/proj/celery
├── celeryconfig.py
├── celery.py
├── __init__.py
└── tasks.py
主程序celery.py
#拒绝隐式引入,因为celery.py的名字和celery的包名冲突,需要使用这条语句让程序正常运行,否则“from celery import Celery”这条语句将会报错,因为首先找到的celery.py文件中并没有Celery这个类
from __future__ import absolute_import
from celery import Celery
# app是Celery类的实例,创建的时候添加了celery.tasks这个模块,也就是包含了celery/tasks.py这个文件
app = Celery('celery',include=['celery.tasks'])
# 把Celery配置存放进celery/celeryconfig.py文件,使用app.config_from_object加载配置
app.config_from_object('celery.celeryconfig')
if __name__ == "__main__":
app.start()
存放任务函数的文件task.py
from __future__ import absolute_import
from celery.celery import app
@app.task
def add(x, y):
return x+y
tasks.py只有一个任务函数add,让它生效的最直接的方法就是添加app.task这个装饰器。celery配置文件celeryconfig.py:
# 使用Redis作为消息代理
BROKER_URL = 'redis://192.168.189.100:6379/0'
# 把任务结果保存在Redis中
CELERY_RESULT_BACKEND = 'redis://192.168.189.100:6379/1'
# 任务序列化和反序列化使用msgpack方案
CELERY_TASK_SERIALIZER = 'msgpack'
# 读取任务结果一般性能要求不高,所以使用了可读性更好的JSON
CELERY_RESULT_SERIALIZER = 'json'
# 任务过期时间,这样写更加明显
CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24
# 指定接受的内容类型
CELERY_ACCEPT_CONTENT = ['json', 'msgpack']
celery与定时任务
celery支持定时任务,设定好任务的执行时间,celery就会定时自动帮你执行, 这个定时任务模块叫celery beat。写一个脚本 叫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 会添加一条定时任务,上面是通过调用函数添加定时任务,也可以像写配置文件 一样的形式添加, 下面是每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
1 $ 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)
此时还差一步,就是还需要启动一个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