Python-模块和包.深入Celery之Beat触发定时/周期性任务

来源:互联网 发布:北京大数据培训班 编辑:程序博客网 时间:2024/06/01 07:34

任务调度:

1. Celery默认任务单元由任务生产者触发,但有时可能需要其自动触发,而Beat进程正是负责此类任务,能够自动触发定时/周期性任务.

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

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @Date    : 2016-12-24 17:32:54

# @Author  : 李满满 (xmdevops@vip.qq.com)

# @Link    : http://xmdevops.blog.51cto.com/

# @Version : $Id$

from __future__ import absolute_import

# 说明: 导入公共模块

from datetime import timedelta

from kombu import Queue, Exchange

from celery.schedules import crontab

# 说明: 导入其它模块

# BROKER_URL = 'amqp://root:qwertyuiop@172.24.10.1:5672//'

# CELERY_RESULT_BACKEND = 'redis://172.24.10.1:6379/0'

BROKER_URL = 'amqp://root:qwertyuiop@10.2.5.51:5672//'

CELERY_RESULT_BACKEND = 'redis://10.2.5.51:5123/0'

CELERY_TASK_SERIALIZER = 'msgpack'

CELERY_RESULT_SERIALIZER = 'json'

CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24

CELERY_ACCEPT_CONTENT = ['json''msgpack']

CELERYD_MAX_TASKS_PER_CHILD = 40

CELERYBEAT_SCHEDULE = {

    'send_mail': {

        'task''work.notify.email.send_mail',

        # 'schedule': timedelta(minute=1),

        'schedule': crontab(minute='*/1'),

        'args': ('usr''sub''msg')

    }

}

说明: 任务调度主要是为了解决业务场景中定时或周期任务,分别使用timedelta和crontab来定义计划任务,crontab的精度无法精确到秒时可使用timedelta代替,CELERYBEAT_SCHEDULE下可以定义多个计划/周期任务,send_mail为任务名称,task为任务单元导入名,schedule为具体调度,args为任务单元的参数.

注意: 运行时可先启动work进程池(celery worker -A work.app -l info)然后再启动beat进程池(celery beat -A work.app -l info),观察会发现beat进程每分钟生成一个任务,work进程发现任务后立即执行

扩展: Django-celery可实现在管理后台添加,删除,更新任务,是因为它使用了自定义的调度类djcelery.schedulers.DatabaseScheduler,Flask没有所以可以参考它来完成同样的功能.

 

原文转自:乐搏学院http://www.learnbo.com/
原创粉丝点击