You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Celery定时任务中每发送20封邮件后休眠1秒实现方案咨询

实现每20封邮件休眠1秒的Celery任务改造方案

核心思路

将原批量发送逻辑拆分为单封循环发送,引入计数器跟踪发送次数,每完成20次发送后触发1秒休眠,避免邮件服务器因短时间接收大量请求而限流。

完整改造代码

import time
# 保持你原有的Celery app引用,比如:
# from your_celery_module import app

@app.task(bind=True)
def send_email_reminder_due_date(self):
    # 第一步:获取当日待发送的所有记录(替换为你实际的查询逻辑)
    # 示例:每条记录包含收件邮箱和对应模板数据
    daily_records = fetch_daily_due_records()
    
    send_counter = 0
    for record in daily_records:
        # 提取当前邮件的收件人和专属模板数据
        target_email = record["recipient_email"]
        custom_template_data = record["template_context"]  # 替换为你的模板数据生成逻辑
        
        # 发送单封邮件
        send_email_from_template(
            subject_template_path='emails/0.txt',
            body_template_path='emails/1.html',
            template_data=custom_template_data,
            to_email_list=[target_email],  # 改为单收件人,确保每次调用计数1次
            fail_silently=False,
            content_subtype='html'
        )
        
        send_counter += 1
        # 每发送满20封后休眠1秒
        if send_counter % 20 == 0:
            time.sleep(1)

关键细节说明

  • 计数独立性:每次任务启动时send_counter从0重置,确保每日任务的计数不受之前执行影响。
  • 单封发送调整:若原send_email_from_template支持批量发送,需将to_email_list改为单元素列表,保证每次调用对应1次发送计数。
  • 休眠时机控制:send_counter % 20 == 0会在第20、40、60...封发送完成后触发休眠,完全匹配“执行满20次休眠”的需求。
  • 可选容错优化:如果需要避免失败邮件占用计数名额,可将发送逻辑包裹在try-except块中,仅在发送成功时递增计数器。

内容的提问来源于stack exchange,提问作者jimmy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:15:48