Reputation: 37
I have a trigger which runs an apps script function every 5 minutes. Sometimes, maybe 1 in 10, the function takes over 5 minutes (but less than 6) to run. If this is the case, I do not want the trigger to run the function again because it will be repeating what is currently being done. I want it to wait another minute and then run. How can I check if the function is running and use this to allow or disallow the trigger? Also notice that my script mostly runs around 3 or 4 minute mark (the very short entries are a different function) so if I could be more efficient and trigger again sooner if it finishes early, that would be amazing.
Upvotes: 3
Views: 2558
Reputation: 31300
Put a value into Cache that lasts 10 minutes. At the end of the code, remove the Cache property. When the code runs, try to get the value out of cache, if it's there, then quit. I'd use Cache Service instead of Properties Service because if the code fails and the value in Properties Service doesn't get changed or deleted, then you're code could stop running altogether. Cache will timeout at the set time regardless of whether the code completes or not.
function myCode() {
var isItRunning;
isItRunning = CacheService.getDocumentCache().put("itzRunning", "true",600);//Keep this value in Cache for up to X minutes
//There are 3 types of Cache - if the Apps Script project is not
//bound to a document then use ScriptCache
if (isItRunning) {//If this is true then another instance of this
//function is running which means that you dont want this
//instance of this function to run - so quit
return;//Stop running this instance of this function
}
//Put the code you want to run here
CacheService.getDocumentCache().remove("itzRunning");
}
Upvotes: 4
Reputation: 2004
You can delete the trigger and create a new one that will wait 5 minutes at the end of each execution.
You can check the Managing triggers programmatically to delete and create new triggers.
This is an example of it:
function myFunction() {
//Execute function
Logger.log('executed');
//Delete trigger
var oldTrigger = ScriptApp.getScriptTriggers()
for (var i = 0; i < oldTrigger.length; i++) {
ScriptApp.deleteTrigger(oldTrigger[i]);
break;
}
//Create new trigger
ScriptApp.newTrigger('myFunction').timeBased().everyMinutes(5).create();
}
Upvotes: 0
Reputation: 792
You can use a "Flag" variable with values representing if a Trigger is running or not and store the value using Properties or Cache. '1' = A trigger is running
OR '0' = No trigger is running
function myTrigger() {
var scriptProperties = PropertiesService.getScriptProperties();
// Waits until last trigger is already done
while(scriptProperties.getProperty('flag') == '1')
Utilities.sleep(60000);
// Once started set flag value as '1'
scriptProperties.setProperty('flag', '1');
// Your code...
// Once finished set flag value as '0'
scriptProperties.setProperty('flag', '0');
}
Upvotes: 1