wkt's blog
非学无以致疑,非问无以广识

celery在flask中的使用和celery.schedules选项

admin~2018年9月24日 /flask/其他/笔记

环境:

pip install flask-celery-helper

celery 结合flask

大致四步:

一. 配置app

在Flask对象的config中写入以下配置.

class CelerySetting(object):
    # celery
    CELERY_BROKER_URL = 'redis://localhost:6379',
    CELERY_RESULT_BACKEND = 'redis://localhost:6379'
    CELERY_TIMEZONE = 'Asia/Shanghai'
    CELERYBEAT_SCHEDULE = {
        'close_redpkg': {
            'task': 'close_redpkg',
            'schedule': timedelta(minutes=5)
        },
        'delete_pkg': {
            'task': 'delete_pkg',
            'schedule': timedelta(minutes=5)
        },
        'total_score': {
            'task': 'total_score',
            'schedule': crontab(minute=55)
        }
    }
app.config.from_object(CelerySetting)

二. 实例化Celery对象并绑定app

from flask_celery import Celery
celery = Celery()
celery.init_app(app)

三. 定时任务

定时任务的装饰器参数应与app配置中一致

@celery.task(name='total_score')
def total_score():
    """统计整点积分"""
    session = db_session()
    try:
        total = TodayTotalScore()
        users = session.query(UserScore).all()
        total.TTSid = str(uuid.uuid4())
        total.TTSvalue = sum([x.SCnum for x in users])
        total.TTStotaluser = len(users)
        session.add(total)
        session.commit()
    except Exception as e:
        # 记录日志
        session.rollback()
        print('celete')
    finally:
        session.close()

四. 启动

celery worker -l INFO -c 1 -A flaskrun.celery --beat

: 请确保在启动文件里可以找到celery对象

关于schedules配置说明

文档:

本次使用:

#...
  'schedule': crontab(hour=7, minute=30, day_of_week=1),
'schedule': timedelta(seconds=5)

其他:

centos下安装redis: https://www.jianshu.com/p/ebda253a8daa

发表评论

电子邮件地址不会被公开。