我正在设置一个应该在每月最后一天触发的时间触发器,在设置脚本时,我遇到了以下情况:
如果我选择本月的
31st day
,那么我相信它会在31st of December
运行良好,但是February
只有28 or 29
天,那么它会如何触发,因为它被设置为在每月 31 日而不是 29 日,非常感谢任何解决此混乱的指导或参考。
我相信您的目标如下。
虽然我不确定您当前的脚本,但在您的情况下,以下示例脚本怎么样?
在此示例脚本中,假设函数
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
时,将运行以下流程。
sampleFunction
在“2023-12-31 00:00:00”运行时,下一个触发器设置为“2024-01-31 00:00:00”。sampleFunction
在“2024-01-31 00:00:00”运行时,下一个触发器设置为“2024-02-29 00:00:00”。