celery多实例与多任务

来源:互联网 发布:maple软件要钱吗 编辑:程序博客网 时间:2024/06/05 01:03
  1. celery多实例
    简单的项目目录结构如下:
    /root/test/proj/celery├── celeryconfig.py├── celery.py├── __init__.py└── tasks.py
    主程序celery.py
    #!/usr/bin/env python#coding:utf8#拒绝隐式引入,因为celery.py的名字和celery的包名冲突,需要使用这条语句让程序正常运行,否则“from celery import Celery”这条语句将会报错,因为首先找到的celery.py文件中并没有Celery这个类from __future__ import absolute_importfrom 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
    #!/usr/bin/env python#coding:utf8from __future__ import absolute_importfrom celery.celery import app@app.taskdef 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'# 读取任务结果一般性能要求不高,所以使用了可读性更好的JSONCELERY_RESULT_SERIALIZER = 'json'# 任务过期时间,这样写更加明显CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24# 指定接受的内容类型CELERY_ACCEPT_CONTENT = ['json', 'msgpack']

  2. celery与定时任务

    celery支持定时任务,设定好任务的执行时间,celery就会定时自动帮你执行, 这个定时任务模块叫celery beat。写一个脚本 叫periodic_task.py

    from celery import Celeryfrom celery.schedules import crontab app = Celery() @app.on_after_configure.connectdef 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.taskdef 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:31Configuration ->    . 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


原创粉丝点击