首页 > 解决方案 > 使用特定时间段触发 Google 脚本

问题描述

我想在特定时间段每 15 分钟触发一次谷歌脚本,即上午 9:30 - 下午 4:30 和晚上 9:30 - 上午 5:30,仅限周一至周五。

我希望脚本在触发时发送电子邮件。我写了一些代码(从谷歌搜索),它成功地向我发送了电子邮件,但我不知道如何在我上面提到的特定时间段内触发脚本。这是我第一次尝试编写代码,但我不知道该怎么做。我用谷歌搜索它,但我的代码不起作用。所以,我来这里寻求帮助。非常感谢。

标签: google-apps-script

解决方案


为特定时间段设置 Apps 脚本触发器是不可行的(或非常复杂)

更简单的方法是将其设置为everyMinutes(n),然后在触发时运行的函数中实现一个条件语句来决定是否发送电子邮件

示例(将其与您要实现的条件仔细比较):

//run only once:
function createTrigger(){
  ScriptApp.newTrigger("runOnTrigger")
  .timeBased()
  .everyMinutes(15)
  .create();
}
function runOnTrigger(){
  var date = new Date();
  var weekDay = date.getDay();
  var hours = date.getHours();
  var minutes = date.getMinutes();

  //stop execution if it's a weekday
  if(weekDay == 0 || weekDay == 6){
    return;
  }
  // stop execution if it's between 4:30pm and 9:30pm
  if(((hours == 16 && minutes >= 30) || hours >= 17) && ((hours == 21 && minutes <= 30) || hours < 21)){
    return;
  }
// stop execution if it's between 9:30pm and 5:30 am
  if(((hours == 5 && minutes >= 30) || hours > 6) && ((hours == 16 && minutes <= 30) || hours < 16)){
    return;
  }
// implement here your request (e.g. sending emails) that shall be run if you are in the correc time slot
}

推荐阅读