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.

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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With