Celery异步任务

2016/05/19 Celery 阅读次数:

异步任务队列

在项目中创建celery_tasks包,里面创建tasks.py文件,用作执行异步任务

使用celery

from django.conf import settings
from django.core.mail import send_mail
# 导入Celery类
from celery import Celery

# 这两行代码在启动worker进行的一端打开
# 设置django配置依赖的环境变量
# import os
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh.settings")

# 创建一个Celery类的对象
app = Celery('celery_tasks.tasks', broker='redis://172.16.179.142:6379/11')


# 定义任务函数
@app.task
def send_register_active_email(to_email, username, token):
    """发送激活邮件"""
    # 组织邮件内容
    subject = '欢迎'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = """
    <h1>%s, 欢迎您注册会员</h1>
    请点击以下链接激活您的账户<br/>
    <a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
    """ % (username, token, token)
    
    # 发送激活邮件
    # send_mail(subject=邮件标题, message=邮件正文,from_email=发件人, recipient_list=收件人列表)
    import time
    time.sleep(5)
    send_mail(subject, message, sender, receiver, html_message=html_message)

Search

    Table of Contents