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

为邮件数组生成工作日6-18点均匀分配的send_at时间戳

解决方案

核心逻辑说明

要实现邮件在工作日6:00-18:00时段内均匀分配,关键要做好三点:

  • 锁定起始时间戳:找到最近的工作日6:00,自动避开周末和非目标时段
  • 计算时间间隔:用12小时的总毫秒数除以(邮件总数-1),保证第一封在6点、最后一封在18点,中间邮件均匀分布
  • 批量生成对应时间戳:给每封邮件分配「起始时间 + 索引×间隔」的时间戳

完整实现代码

function myFunction(emailList) {
  const emailCount = emailList.length;
  if (emailCount === 0) return [];

  // 获取最近的工作日6:00时间戳
  function getNextWorkday6AM() {
    const now = new Date();
    let target = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0);
    
    // 如果当前时间已过当天6点,先往后推一天
    if (now > target) {
      target.setDate(target.getDate() + 1);
    }
    
    // 调整到周一至周五的工作日
    while (target.getDay() === 0 || target.getDay() === 6) {
      target.setDate(target.getDate() + 1);
    }
    
    return target.getTime();
  }

  const startTime = getNextWorkday6AM();
  const endTime = startTime + 12 * 3600 * 1000; // 12小时后即当日18:00
  const interval = emailCount === 1 ? 0 : (endTime - startTime) / (emailCount - 1);

  return emailList.map((email, index) => {
    // 取整为毫秒级整数时间戳
    const sendAt = Math.round(startTime + index * interval);
    return { email, send_at: sendAt };
  });
}

// 500条邮件示例调用
const testEmails = Array.from({ length: 500 }, (_, i) => `user${i+1}@example.com`);
const scheduledEmails = myFunction(testEmails);
console.log(scheduledEmails);

代码细节说明

  • getNextWorkday6AM函数:自动处理「当前时间过晚」「当前是周末」等边界情况,确保起始时间符合要求
  • 间隔计算逻辑:单封邮件直接用起始时间;多封邮件时用总时长除以(数量-1),避免最后一封邮件超出18:00时段
  • 时间戳取整:用Math.round保证结果为整数毫秒,符合标准时间戳格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:09:25