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

Google Apps Script每日触发器重复执行致Slack消息重复的解决方案咨询

解决Google Apps Script每日触发器重复执行发送Slack消息的问题

你的问题核心是重复创建了多个同类型触发器,导致每日9点时多个触发器同时触发,发送重复消息。以下是两种可行的解决思路:


1. 创建触发器前先清理旧触发器

每次调用setTrigger时,先删除所有已存在的、关联sendBirthdayMessage函数的触发器,确保始终只有一个每日触发器存在:

function setTrigger() {
  // 遍历所有项目触发器,删除目标函数的旧触发器
  const existingTriggers = ScriptApp.getProjectTriggers();
  for (const trigger of existingTriggers) {
    if (trigger.getHandlerFunction() === 'sendBirthdayMessage') {
      ScriptApp.deleteTrigger(trigger);
    }
  }

  // 创建新的每日9点触发器
  ScriptApp.newTrigger('sendBirthdayMessage')
    .timeBased()
    .everyDays(1)
    .atHour(9)
    .nearMinute(0)
    .create();
}

2. 在消息发送函数中添加当日执行校验

如果担心Google服务偶尔出现的触发器重复触发异常,可以在sendBirthdayMessage中加入日期校验,用脚本属性存储最后执行日期,确保一天内只发送一次:

function sendBirthdayMessage() {
  const props = PropertiesService.getScriptProperties();
  const today = new Date().toDateString(); // 格式如 "Wed Oct 11 2023"
  const lastExecutedDate = props.getProperty('lastBirthdayMessageDate');

  // 当日已执行过则直接退出
  if (lastExecutedDate === today) {
    return;
  }

  // 这里写你的Slack Webhook发送逻辑
  // 示例:
  // const webhookUrl = '你的Slack Webhook地址';
  // const payload = { text: '今日生日祝福消息' };
  // UrlFetchApp.fetch(webhookUrl, {
  //   method: 'post',
  //   contentType: 'application/json',
  //   payload: JSON.stringify(payload)
  // });

  // 更新最后执行日期为今日
  props.setProperty('lastBirthdayMessageDate', today);
}

两种方案可以结合使用,从“避免重复创建触发器”和“避免重复执行发送逻辑”两个层面彻底解决重复消息问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:55:12