Scheduling Google App Script function for specific recurring windows [duplicate]

不打扰是莪最后的温柔 提交于 2021-02-10 17:48:57

问题


I'm trying to schedule an Apps Script function. I need the email to trigger Mon-Sat every 2 hours starting at 11am-9pm.

I've written the following code to create triggers for each day:

function createTriggers() {

  var days = [ScriptApp.WeekDay.MONDAY, 
              ScriptApp.WeekDay.TUESDAY,
              ScriptApp.WeekDay.WEDNESDAY, 
              ScriptApp.WeekDay.THURSDAY, 
              ScriptApp.WeekDay.FRIDAY,
              ScriptApp.WeekDay.SATURDAY];

  for (var i=0; i<days.length; i++) { 
    ScriptApp.newTrigger('emailDashboard')
      .timeBased().onWeekDay(days[i])
      .everyWeeks(1).everyHours(2).create();
  }
}

When I run what I have above, I get the following error:

"The recurrence interval on the clock trigger has already been set. (line 79, file "Code")"

I cant find anything about that response, and it doesn't actually create the trigger. I assume what I have above would get me the email Mon-Sat, every 2 hours. I'm not sure how to go about starting at 11am central and ending at 9pm central.


回答1:


Your issue comes from over-specificity. Many of the options you use, like onWeekDay and everyWeeks, are mutually exclusive. You can read more about the class on its Apps Script reference page.

A much simpler approach is to schedule the granularity you desire:

ScriptApp.newTrigger("myFunction").timeBased().everyHours(2).create();

and then check whether the current time meets the criteria you have:

  1. It's not Sunday
  2. Hour greater than 11 am local
  3. Hour less than 9 pm local

It's worth noting that Google will run your function at a minute value of its choosing when you use the hour level of specificity.

As with other triggered functions, there is an available event object

An example discriminator that assumes you only care about UTC values (which are the locale for all values in the event object):

function getsCalledByClockTrigger(e) {
  if(!e) throw new Error("Called from the Script Editor");
  else console.log(e); // Show this event object in Stackdriver logs.

  // Check that it isn't UTC Sunday.
  if(e["day-of-week"] === 7)
    return;

  // Checking the UTC hour is between 11 AM and 9 PM.
  if(e.hour < 11 || e.hour > 21)
    return;

  /* Do stuff */
}

A discriminator for non-UTC values would probably be simplest with var now = new Date() and checking various Date properties like now.getDay().



来源:https://stackoverflow.com/questions/49781711/scheduling-google-app-script-function-for-specific-recurring-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!