Skip to content

Instantly share code, notes, and snippets.

@Max-Makhrov
Last active December 11, 2021 17:39
Show Gist options
  • Save Max-Makhrov/8c82d6334136bc01e4dd0a1f8613c456 to your computer and use it in GitHub Desktop.
Save Max-Makhrov/8c82d6334136bc01e4dd0a1f8613c456 to your computer and use it in GitHub Desktop.
// 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