Google Apps Script 基于时间的触发器在自定义日期和时间基于电子表格中的值

Google Apps Script Time based trigger at custom date and time based on value in spreadsheet

我正在尝试创建一个 Google 应用程序脚本,该脚本能够根据电子表格中的值在特定时间安排邮件。将根据多个日期时间单元格进行触发。我尝试使用 ScriptApp.newTrigger() 以编程方式添加触发器,但我不知道该函数何时创建它应该 运行。任何关于如何解决这个问题的见解都会很棒。

编辑: 当用户像这样提交表单时创建触发器。

function saveForm(form) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test');

  const now = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");

  const newRow = [now, form.cid, form.custName, form.custNumber, form.goodsType, form.tonnage, form.area, form.completeAddr, `${now} - ${form.time}`, form.comments];
  sheet.appendRow(newRow); 

  const customDate = new Date(`${now}T${form.time}`);

  ScriptApp.newTrigger('dispatchMail').timeBased().at(customDate).create();


  return 'Data saved successfully';
}

现在发送邮件的功能

  function dispatchMail() {
       const now = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");

      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test');
      const data = sheet.getDataRange().getValues();

      const normalized = {
               'Mark': [],
               'Jack': [],
               'Chloe': [],
               'Robin': [],
               'Unassigned': []
      };

      for(let i=1; i<data.length; i++) {
          normalized[data[i][10]] = normalized[data[i][10]].concat([data[i]]);
      }

     //start our mail dispatch here once we have aggregated the data
  }

但现在的问题是不知道将邮件发送给谁。例如,用户提交表单时,邮件触发器计划在下午 2 点发送给马克,在下午 4 点发送给杰克。现在在发送邮件功能中如何确定这封邮件是发送给马克还是杰克。我没有看到将参数传递给触发函数的方法。有什么办法可以解决这个问题吗?

如果您的问题与确定触发器 运行 时应执行的内容有关,您可能需要更改处理方法。

与其为每条消息创建一个触发器,不如让一个触发器检查是否需要发送消息。

您可以:

  • 创建一个函数:
    • 过滤掉已发送的消息
    • 查找 target send time 过去的邮件
    • 发送那些消息
  • 为 运行 该函数创建一个基于时间的触发器。

请记住,在最好的情况下,您的消息将在目标时间发送,在最坏的情况下,它将在 <interval between trigger runs> 时间发送。

此外,您还需要跟踪已发送的内容(例如,使用额外的列或删除行)