django之使用celery


##########django之使用celery##############
1.首先在目录:/项目/applition/celery.py添加以下内容
import os

import django
from celery import Celery, platforms
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', "application.settings")
django.setup()

app = Celery(f"dvadmin")

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
platforms.C_FORCE_ROOT = True
2.在:/项目applition/__init__.py添加以下内容
from .celery import app

__all__ = ['app']
3.然后在你自己的模块的tasks.py写任务
import time

from celery import shared_task

@shared_task
def task_demo(name):
    print(f"给{name}发邮件。。。。。")
    time.sleep(50)
    print(f"给{name}发邮件完成")
    return "OK"

4.在视图中调用此任务
result1 = task_demo.delay("wusen")
print(f"CELERY_ID:{result1.id}")

5.在窗口启动
celery  -A application worker  -l debug -P eventlet

相关