I am sharing a google script sheet to multiple users, I just want to prevent the same user to run the script at the same time. What do I have to do? Is it by code or by settings only?
As @TheMaster said in a comment, LockService is the way to go. Specifically, you want LockService.getDocumentLock() or LockService.getScriptLock() depending on how your script is set up.
Example of how to use the lock service in Apps Script:
var timeoutMs = 5000; // wait 5 seconds before giving up
var lock = LockService.getScriptLock(); // or LockService.getDocumentLock();
lock.tryLock(timeoutMs);
try {
if (!lock.hasLock()) {
var msg = 'Skipped execution after ' + (timeoutMs / 1000).toString() + ' seconds; script already running.';
console.log(msg);
try {
// If script is being run from a user UI context (ex: from a Menu option),
// gracefully alert the user we gave up
SpreadsheetApp.getUi().alert(msg);
} catch (e2) {}
} else {
//*** ADD CODE YOU WANT TO PROTECT HERE
}
} catch (e) {
console.error(e);
try {
var ui = SpreadsheetApp.getUi();
ui.alert("Error", e ? e.toString() : e, ui.OK);
} catch (e2) {}
}
SpreadsheetApp.flush();
lock.releaseLock();
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