使用 Google Apps 脚本设置时间触发器时的最后一个月的复杂性

问题描述 投票:0回答:1

我正在设置一个应该在每月最后一天触发的时间触发器,在设置脚本时,我遇到了以下情况:

如果我选择本月的

31st day
,那么我相信它会在
31st of December
运行良好,但是
February
只有
28 or 29
天,那么它会如何触发,因为它被设置为在每月 31 日而不是 29 日,非常感谢任何解决此混乱的指导或参考。

google-apps-script google-sheets triggers
1个回答
0
投票

我相信您的目标如下。

  • 您想要使用 Google Apps 脚本将时间驱动的触发器安装到每月的最后一天。

虽然我不确定您当前的脚本,但在您的情况下,以下示例脚本怎么样?

示例脚本:

在此示例脚本中,假设函数

sampleFunction
是您要运行的函数。并且,函数
installTrigger
用于安装下一个时间驱动触发器。

请将以下脚本复制并粘贴到脚本编辑器中。并且,请设置

time
。在此示例中,脚本在“00:00”运行。并且,请将您的脚本设置为
sampleFunction
。并且,请运行
installTrigger
。这样,就安装了下一个触发器。

当然,即使您运行

sampleFunction
,下一个触发器也会安装并且您的脚本也会运行。

// This is a function you want to run.
function sampleFunction() {
  installTrigger(); // Please set this.

  // Please put your script.
  // do something

}

function installTrigger() {
  const functionName = "sampleFunction"; // Please set the function name you want to run with the trigger.
  const time = "00:00:00"; // Please set the time you want to run.

  // Delete existing triggers.
  ScriptApp.getProjectTriggers().forEach(t => {
    if (t.getHandlerFunction() == functionName) {
      ScriptApp.deleteTrigger(t);
    }
  });

  // Set new trigger.
  const date = new Date();
  const d = date.getDate();
  const month = date.getMonth();
  date.setMonth(month + 1, 0);
  date.setHours(...time.split(":"));
  if (date.getDate() == d) {
    date.setMonth(month + 2, 0);
  }
  ScriptApp.newTrigger(functionName).timeBased().at(date).create();

  console.log(date); // You can see the trigger date in the log.
}
  • 修改函数名称时

    sampleFunction
    ,请同时修改
    const functionName = "sampleFunction";

  • 例如,当今天是“2023-12-30”并运行

    installTrigger
    时,将运行以下流程。

    1. 安装时间驱动触发器“2023-12-31 00:00:00”。
    2. 当函数
      sampleFunction
      在“2023-12-31 00:00:00”运行时,下一个触发器设置为“2024-01-31 00:00:00”。
    3. 当函数
      sampleFunction
      在“2024-01-31 00:00:00”运行时,下一个触发器设置为“2024-02-29 00:00:00”。
    4. 此循环已运行。

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.