Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// The function may be used to prevent conflicting launches
function test_PreventConflict() {
// Lock(1). Use Script memory
var key = 'any-key-you-want';
var mem = PropertiesService.getScriptProperties();
// Lock(2). Check if other instance of the code is running
var from = mem.getProperty(key);
if (from) {
var json = JSON.parse(from);
var tnow = new Date(); // current date
var twas = new Date(json.d); // date from the same function, from memory
// in minutes
var diffMinutes = parseInt((tnow.getTime() - twas.getTime())/(1000 * 60));
// Check in case original script was broken and 10 minutes passed
if (diffMinutes < 10) { // change 10 to yoor number. It shouldn't be more than usual runtime
// the function is still running. No launch again
Logger.log('Stopped thre function to prevent conflict');
return -1;
}
}
// Lock(3). Save status - in. Will be in memory while function is running
mem.setProperty(key, JSON.stringify({d: new Date()}));
// Main function. the function...
Utilities.sleep(5000); // change this line with your useful code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Lock(4).Release conflict
mem.deleteProperty(key);
Logger.log('The function is finished. Success!');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment