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

Node.js中基于WhatsApp API实现定时批量消息的最优方案咨询

可行的定时消息方案(Node.js + WhatsApp API)

针对批量定时发送WhatsApp消息的需求,以下几个方案比setTimeout更可靠、可扩展:

1. 使用专业定时任务库(node-schedule)

适合中小规模的定时任务,配置简单,支持复杂的 cron 表达式,能应对单次/重复定时需求。

示例代码:

const schedule = require('node-schedule');
const whatsappClient = require('./your-whatsapp-client'); // 你的WhatsAPI客户端实例

// 定义批量定时任务:每天早上8点给指定用户发消息
const job = schedule.scheduleJob('0 8 * * *', async () => {
  const userList = ['+1234567890', '+0987654321']; // 批量用户列表
  for (const phone of userList) {
    try {
      await whatsappClient.sendMessage(phone, '早上好!这是定时推送的消息');
      console.log(`消息已发送给 ${phone}`);
    } catch (err) {
      console.error(`发送给 ${phone} 失败:`, err);
      // 可添加重试逻辑或记录失败任务
    }
  }
});

// 若需取消任务:job.cancel();

注意点:

  • 若服务重启,未执行的任务会丢失,适合能接受短暂中断的场景,或配合进程守护工具(如PM2)自动重启后重新加载任务。
  • 批量发送时注意WhatsApp API的速率限制,避免触发限流。

2. 结合消息队列实现延迟任务(BullMQ)

适合高并发、需要持久化、重试机制的批量定时场景,即使服务重启,任务也不会丢失,还能监控任务状态。

示例代码:

const { Queue, Worker } = require('bullmq');

// 创建延迟队列
const whatsappQueue = new Queue('whatsapp-scheduled-messages', {
  connection: {
    host: 'localhost',
    port: 6379 // Redis连接配置,BullMQ依赖Redis
  }
});

// 添加定时任务到队列(比如30分钟后发送)
async function addScheduledMessage(phone, message, delayMs) {
  await whatsappQueue.add('send-message', { phone, message }, {
    delay: delayMs,
    attempts: 3, // 失败重试3次
    backoff: { type: 'exponential', delay: 1000 } // 指数退避重试
  });
}

// 启动Worker处理队列任务
const worker = new Worker('whatsapp-scheduled-messages', async (job) => {
  const { phone, message } = job.data;
  const whatsappClient = require('./your-whatsapp-client');
  await whatsappClient.sendMessage(phone, message);
  return `消息发送成功: ${phone}`;
}, {
  connection: { host: 'localhost', port: 6379 }
});

// 监听任务状态
worker.on('completed', (job) => {
  console.log(`任务 ${job.id} 完成:`, job.returnvalue);
});

worker.on('failed', (job, err) => {
  console.error(`任务 ${job.id} 失败:`, err);
});

// 调用示例:30分钟后给用户发消息
addScheduledMessage('+1234567890', '这是30分钟后的定时消息', 30 * 60 * 1000);

注意点:

  • 需要部署Redis作为存储,确保任务持久化。
  • 天然支持批量任务的并发处理,可通过配置Worker数量控制发送速率,避免触发WhatsApp API的限流。

3. 数据库持久化+自定义调度器

适合高度定制化的场景,比如需要在数据库中管理定时任务的创建、修改、取消。

核心思路:

  • 在数据库中创建scheduled_messages表,字段包含phone、message、send_time、status(待发送/已发送/失败)。
  • 启动一个定时轮询的进程(比如每分钟一次),查询当前时间已到且状态为待发送的任务。
  • 批量处理这些任务,更新状态,失败则标记并记录重试次数。

示例代码(伪代码):

const cron = require('node-cron');
const db = require('./your-db-connection'); // 你的数据库连接(如MySQL/MongoDB)
const whatsappClient = require('./your-whatsapp-client');

// 每分钟轮询一次数据库
cron.schedule('* * * * *', async () => {
  const now = new Date();
  // 查询待发送的定时任务
  const tasks = await db.scheduledMessages.find({
    send_time: { $lte: now },
    status: 'pending'
  });

  for (const task of tasks) {
    try {
      await whatsappClient.sendMessage(task.phone, task.message);
      await db.scheduledMessages.updateOne({ _id: task._id }, { status: 'sent' });
      console.log(`任务 ${task._id} 发送成功`);
    } catch (err) {
      await db.scheduledMessages.updateOne(
        { _id: task._id },
        { 
          status: 'failed',
          retry_count: (task.retry_count || 0) + 1,
          error: err.message
        }
      );
      console.error(`任务 ${task._id} 发送失败:`, err);
    }
  }
});

注意点:

  • 轮询频率可根据需求调整,避免过于频繁查询数据库。
  • 可添加重试逻辑,比如当retry_count小于3时,更新send_time为当前时间+5分钟,重新标记为pending。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:10:50