Reputation: 321
I have a Google Sheets spreadsheet and a script needs to update it automatically. Need to run a Google Script only weekdays, every hour, between certain hours - using time-based trigger? Thus run script Monday to Friday from 8am to 5pm, every hour.
Upvotes: 0
Views: 2010
Reputation: 589
Just add a condition that stops execution if the day is Saturday or Sunday
OR the hour is before 8 or after 17
.
function myFunction () {
var today = new Date();
var day = today.getDay();
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
if(day == 6 || day == 0) {
message.innerHTML = 'Today is ' + days[day] + '. So I\'ll do nothing'
return;
} else {
var hour = today.getHours();
var minute = today.getMinutes();
if(hour < 8 || hour > 17) {
message.innerHTML = 'Today is ' + days[day] + ' but the time is ' + hour + ':' + minute + '. So I\'ll do nothing'
return;
}
message.innerHTML = 'Today is ' + days[day] + ' and the time is ' + hour + ':' + minute + '. So I\'ll do something'
}
}
myFunction()
<span id="message"></span>
With this implementation, you just need to create a trigger to run the function once per hour. The condition in the if statements will make sure that any code written below that will not run if it doesn't meet your runtime criteria.
Upvotes: 1
Reputation: 321
This is what I was trying but not working...
function setWeekdaysTrigger() {
var startHour = 8;
var endHour = 17;
var daysWeek = []; //put Enums for days of the week here;
//set trigger to specific week days;
daysWeek.forEach(function(day){
//set trigger for 9AM to 13PM;
for(var h=startHour; h<endHour; h++) {
var tg = ScriptApp.newTrigger('TheScriptToRun').timeBased();
tg.onWeekDay(day);
tg.atHour(h).nearMinute(1).create(); //arbitrary precision (minutes);
}
});
}
Upvotes: 0