Celery(异步任务)(续)
2. 任务层(接口)
# emails/tasks.py
from celery import shared_task
from styleguide_example.emails.models import Email
@shared_task
def email_send(email_id):
"""
邮件发送任务
这个任务很薄,只做两件事:
1. 获取数据
2. 调用服务
"""
# 1. 获取需要的数据
email = Email.objects.get(id=email_id)
# 2. 调用服务(在函数体内导入,避免循环导入)
from styleguide_example.emails.services import email_send
email_send(email)
📝 关键点解析
任务的角色:
- ✅ 作为 API - 接收参数(通常是 ID)
- ✅ 获取必要的数据
- ✅ 调用适当的服务
- ❌ 不包含业务逻辑
为什么在任务内部导入服务?
# ✅ 推荐:在函数体内导入
@shared_task
def email_send(email_id):
from styleguide_example.emails.services import email_send
# ...
# ❌ 不推荐:在模块顶部导入
from styleguide_example.emails.services import email_send
@shared_task
def email_send_task(email_id):
# ...
原因:
- ✅ 避免循环导入(services 可能导入 tasks)
- ✅ 延迟导入,只在任务执行时才导入
3. 触发任务
现在,假设我们有另一个服务,需要触发邮件发送: