Monday, 18 March 2019

Email scheduler for Gmail - delete trigger

Overview blog post.

The following Google Apps Script code is designed to delete a specific project trigger from a given trigger ID. In the email scheduler it is called upon by a few different functions to ensure redundant triggers do not remain - as other than their scheduled dates they will all appear identical due to them running the same sendEmail function.

We start by getting all of the existing project triggers:
var allTriggers = ScriptApp.getProjectTriggers();
From this array we can then loop through each in turn and 'getUniqueID' to compare it with the value we have stored in the spreadsheet - to look for a match:
if (allTriggers[i].getUniqueId() == triggerID)
Once we have a match we can 'deleteTrigger' and break the loop so it does not continue to run:
ScriptApp.deleteTrigger(allTriggers[i]);
break;

function deleteTrigger(triggerID) {
// get all existing project triggers
var allTriggers = ScriptApp.getProjectTriggers();
var allTriggersLength = allTriggers.length;
// loop through existing triggers ***************************************
for (var i=0; i<allTriggersLength; i++) {
// if the current trigger is the correct one, delete it and stop script
if (allTriggers[i].getUniqueId() == triggerID) {
Logger.log('TriggerID: '+ allTriggers[i] + ' matches ' + triggerID);
ScriptApp.deleteTrigger(allTriggers[i]);
break;
}
else {
Logger.log('No matches for TriggerID: ' + triggerID);
}
} // end of loop through existing triggers ******************************
}

No comments:

Post a Comment