Currently I used My Trigger with Time-driven->Day timer->7am to 8am (GMT+08:00) and the result, my script run at 7:11:45 AM. It's to early.
My question is it's possible to trigger Google Sheets at exact time like 7:55:00 AM everyday?
Currently I used My Trigger with Time-driven->Day timer->7am to 8am (GMT+08:00) and the result, my script run at 7:11:45 AM. It's to early.
My question is it's possible to trigger Google Sheets at exact time like 7:55:00 AM everyday?
You need the following four functions:
setTrigger()
: This function is responsible for deleting the previous triggers and creating a new trigger for function_Triggered
. The only thing you need to do is to setup a daily trigger for that function before 7am, for example 6-7am. The following functions are just helpers, you don't execute them (manually).
scheduledTrigger(hours,minutes)
: this function accepts the time (hours and minutes) and it is responsible for creating the scheduled trigger for function_Triggered
.
deleteTriggers()
: This function deletes all the current triggers (in this case only one) for function_Triggered
.
function_Triggered()
: this function contains the code that you want to execute everyday at 7:55am.
function setTrigger() {
deleteTriggers();
scheduledTrigger(7,55);
}
function scheduledTrigger(hours,minutes){
var today_D = new Date();
var year = today_D.getFullYear();
var month = today_D.getMonth();
var day = today_D.getDate();
pars = [year,month,day,hours,minutes];
var scheduled_D = new Date(...pars);
var hours_remain=Math.abs(scheduled_D - today_D) / 36e5;
ScriptApp.newTrigger("function_Triggered")
.timeBased()
.after(hours_remain * 60 *60 * 1000)
.create()
}
function deleteTriggers() {
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
if ( triggers[i].getHandlerFunction() == "function_Triggered") {
ScriptApp.deleteTrigger(triggers[i]);
}
}
}
function function_Triggered() {
// your function code here
}