简体   繁体   English

Google Apps 脚本:时间驱动触发器时区问题

[英]Google Apps Script: Time Driven Triggers timezone issue

I'm attempting to build a basic Time Driven Trigger in Google Apps Script to run a function at a specified date and time.我正在尝试在 Google Apps 脚本中构建一个基本的时间驱动触发器,以在指定的日期和时间运行函数。

My code is as follows:我的代码如下:

function createTimeDrivenTriggers() {
ScriptApp.newTrigger('myFunction')
    .timeBased()
    .atDate(2019, 12, 29)
    .atHour(12)
    .nearMinute(5)
    .create();
Logger.log("Trigger started!");
}

function myFunction() {
  Logger.log("I was triggered!");
}

However, each time I try to run the createTimeDrivenTriggers function I get the following error:但是,每次我尝试运行 createTimeDrivenTriggers 函数时,都会收到以下错误:

You cannot schedule an event in the past. (line 7, file "Triggers")

At the time of writing 2019-12-29 12:05 was not in the past (in my timezone).在撰写本文时 2019-12-29 12:05 不是过去(在我的时区)。 This made me think that the script is running in a different timezone than I am.. is that the case?这让我觉得脚本在与我不同的时区运行..是这样吗? If so, how do I set the script to default to the user's timezone?如果是这样,如何将脚本设置为默认为用户的时区?

This script is part of a Google Sheets Add On, I confirmed that my Google Sheets timezone is set to my local.此脚本是 Google Sheets Add On 的一部分,我确认我的 Google Sheets 时区设置为我的本地时区。

How about this answer?这个答案怎么样? Unfortunately, atDate and atHour cannot be used, simultaneously.不幸的是,不能同时使用atDateatHour In your case, atDate is used and the trigger is tried to be installed as 2019-12-29 00:00 .在您的情况下,使用atDate并尝试将触发器安装为2019-12-29 00:00 So such error occurs.所以会出现这样的错误。

When you want to install the time-driven trigger for 2019-12-29 12:05 , how about modifying as follows?当你想安装2019-12-29 12:05的时间驱动触发器2019-12-29 12:05 ,如何修改如下?

Modified script:修改后的脚本:

From: 从:
 ScriptApp.newTrigger('myFunction') .timeBased() .atDate(2019, 12, 29) .atHour(12) .nearMinute(5) .create();
To: 至:
 ScriptApp.newTrigger("myFunction") .timeBased() .at(new Date(2019, 11, 29, 12, 5)) .create();

Note:笔记:

  • In this case, please use 11 for December.在这种情况下,请为 12 月使用11 Because the initial index of month for Date is 0 .因为 Date 的月份的初始索引是0

    monthIndex: Integer value representing the month, beginning with 0 for January to 11 for December. monthIndex:表示月份的整数值,从一月的 0 开始到十二月的 11。 Ref 参考

References:参考:

If this was not the direction you want, I apologize.如果这不是您想要的方向,我深表歉意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM