celery使用

  • 将celery异步任务作为一个单独的文件包

tasks.__init__.py

from celery import Celery


# 使用工厂函数创建celery实例
# http://docs.jinkan.org/docs/flask/patterns/celery.html#id2 参考文档
def make_celery(app):
    celery = Celery('blog')
    # celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

main.py

from . import make_celery
from flask_blog import app
from . import config

# 定义celery对象
celery = make_celery(app)
# 引入配置信息
celery.config_from_object(config)
# 自动搜寻任务
celery.autodiscover_tasks(['tasks.mails'])

config.py

BROKER_URL = 'redis://192.168.4.222:6379/0',
CELERY_RESULT_BACKEND = 'redis://192.168.4.222:6379/1'

tasks.mails.tasks.py

from flask_mail import Message
from datetime import datetime

from blueblog.extensions import mail
from tasks.main import celery


# celery -A 'tasks.send_email' worker
# celery -A "tasks.send_mail".celery worker -l info -P eventlet
@celery.task(bind=True, default_retry_delay=300, max_retries=5 )
def register_mail(self):
    try:
        msg = Message('您好,欢迎您使用本网站', sender='1229122696@qq.com', recipients=['728672772@qq.com'])
        msg.body = str(datetime.now())
        msg.html = '<b>str(datetime.now())</b> stranger'
        mail.send(msg)
    except Exception as e:
        self.retry(e)
    return 'xxxxxx'

http://docs.jinkan.org/docs/flask/patterns/celery.html#id2

 

posted @ 2019-02-28 13:25  20180616  阅读(224)  评论(1编辑  收藏  举报