zoukankan      html  css  js  c++  java
  • Celery--定时任务

    在celery中执行定时任务非常简单,只需要设置celery对象的CELERYBEAT_SCHEDULE属性即可。
     
    周期性任务
    config.py :
    from datetime import timedelta
    CELERY_RESULT_BACKEND
    = 'redis://127.0.0.1:6379/5' BROKER_URL = 'redis://127.0.0.1:6379/6' CELERY_TIMEZONE = 'Asia/Shanghai' CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'proj.tasks.add', 'schedule': timedelta(seconds=30), 'args': (16, 16) }, }
    注意配置文件需要指定时区。这段代码表示每隔30秒执行 add 函数。一旦使用了 scheduler, 启动 celery需要加上-B 参数。
    celery -A proj worker -B -l info
     
    设置多个定时任务
    CELERY_TIMEZONE = 'UTC'
    CELERYBEAT_SCHEDULE = {
        'taskA_schedule' : {
            'task':'tasks.video_compress',
            'schedule':20,
            'args':('video_name1')
        },
        'taskB_scheduler' : {
            'task':"tasks.video_upload",
            "schedule":200,
            "args":(video_name2)
        },
        'add_schedule': {
            "task":"tasks.other",
            "schedule":10,
            "args":('str')
        }
    }

    定义3个定时任务,通过下列命令启动一个定时任务: celery -A tasks beat。使用 beat 参数即可启动定时任务。

     
    crontab
    计划任务当然也可以用crontab实现,celery也有crontab模式。修改 config.py
    from celery.schedules import crontab
    
    CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/5'
    BROKER_URL = 'redis://127.0.0.1:6379/6'
    CELERY_TIMEZONE = 'Asia/Shanghai'
    CELERYBEAT_SCHEDULE = {
      # Executes every Monday morning at 7:30 A.
      'add-every-monday-morning': {
        'task': 'tasks.add',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': (16, 16), 
      },
    }
    scheduler的切分度很细,可以精确到秒。crontab模式就不用说了。
    当然celery还有更高级的用法,比如 多个机器 使用,启用多个 worker并发处理 等。
     
    发送任务到队列中
    apply_async(args[, kwargs[, …]])、delay(*args, **kwargs)http://docs.celeryproject.org/en/master/userguide/calling.html
     
    from celery import Celery
    
    celery = Celery()
    celery.config_from_object('celeryconfig')
    send_task('tasks.test1', args=[hotplay_id, start_dt, end_dt], queue='hotplay_jy_queue') 

  • 相关阅读:
    面向对象
    标准库内置模块
    json迭代器生成器装饰器
    基本数据操作
    列表元组字典字符串操作
    深入了解Spring之IoC
    认识OAuth 2.0及实例
    web.xml中context-param和init-param的区别
    虚拟机centos6网卡配置及提示Device does not seem to be present
    JUC之深入理解ReentrantReadWriteLock
  • 原文地址:https://www.cnblogs.com/absoluteli/p/14016747.html
Copyright © 2011-2022 走看看