【问题标题】:Google Apps Script Time based trigger at custom date and time based on value in spreadsheet基于电子表格中的值的自定义日期和时间的基于 Google Apps 脚本时间的触发器
【发布时间】:2020-02-27 12:38:14
【问题描述】:

我正在尝试创建一个能够根据电子表格中的值在特定时间安排邮件的 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 点为 Mark 和在 4 点为 Jack 提交带有 Mail Trigger 的表单。现在在派发邮件功能中如何确定这封邮件是派发给马克还是杰克。我没有看到将参数传递给触发函数的方法。有什么办法吗?

【问题讨论】:

  • 你好@FatehAK,你介意分享一下关于你的问题的代码吗?干杯!
  • 嗨@ale13 我添加了一些代码供参考
  • 你好@FatehAK,所以让我明白 - 你想根据日期向不同的人发送电子邮件吗?干杯!
  • 基于日期和时间@ale13

标签: javascript google-apps-script google-sheets triggers google-apps-script-api


【解决方案1】:

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

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

你可以:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多