如何为Google Apps Script函数配置指定重复时段的定时触发
Got it, let's get your trigger setup sorted. The challenge here is that Google Apps Script's time-based triggers don't support a "repeat every X hours within a daily window" natively for weekdays. Instead, we'll create individual triggers for each specific time slot you need (every 2 hours between 11:00 and 21:00) across Monday to Saturday.
First, let's add a helper function to delete existing triggers for your emailDashboard function—this prevents duplicate triggers if you run the setup multiple times. Then we'll build out the full trigger creation logic:
// Helper function to delete existing triggers for emailDashboard to avoid duplicates function deleteExistingTriggers() { const triggers = ScriptApp.getProjectTriggers(); for (let i = 0; i < triggers.length; i++) { if (triggers[i].getHandlerFunction() === 'emailDashboard') { ScriptApp.deleteTrigger(triggers[i]); } } } function createTriggers() { // Delete old triggers first to prevent duplicates deleteExistingTriggers(); // Define target weekdays (Monday to Saturday) const days = [ ScriptApp.WeekDay.MONDAY, ScriptApp.WeekDay.TUESDAY, ScriptApp.WeekDay.WEDNESDAY, ScriptApp.WeekDay.THURSDAY, ScriptApp.WeekDay.FRIDAY, ScriptApp.WeekDay.SATURDAY ]; // Define target hours (11:00, 13:00, 15:00, 17:00, 19:00, 21:00) const hours = [11, 13, 15, 17, 19, 21]; // Create a trigger for each weekday + hour combination for (let day of days) { for (let hour of hours) { ScriptApp.newTrigger('emailDashboard') .timeBased() .onWeekDay(day) .atHour(hour) .create(); } } Logger.log('Successfully created ' + (days.length * hours.length) + ' triggers!'); }
Key Notes:
- Time Zone Check: Make sure your script's time zone matches your desired trigger time. You can set this in the script editor via
File > Project properties > Time zone. - Duplicate Prevention: The
deleteExistingTriggersfunction ensures you don't end up with multiple triggers running the same function at the same time. - Trigger Count: This will create 6 weekdays × 6 hours = 36 total triggers, which is well within Google's trigger limits (you can have up to 200 triggers per script project).
Once you run createTriggers() once, all the necessary triggers will be set up to run your emailDashboard function exactly when you need it.
内容的提问来源于stack exchange,提问作者S1ick1

