问题
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:
- It's not Sunday
- Hour greater than 11 am local
- 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