Skip to content

Instantly share code, notes, and snippets.

@pfelipm
Last active May 9, 2021 00:25
Show Gist options
  • Save pfelipm/a93e120bf3622214c03d33added95b04 to your computer and use it in GitHub Desktop.
Save pfelipm/a93e120bf3622214c03d33added95b04 to your computer and use it in GitHub Desktop.
Using LockService to avoid concurrent executions, specially relevant when invoking GAS code from buttons in a spreadsheet.
/**
* Simple demonstration of LockService...
* https://developers.google.com/apps-script/reference/lock
* ...to prevent concurrent executions of a GAS function,
* for example when invoked by a button in a Spreadsheet (rather likely).
* Demo: https://docs.google.com/spreadsheets/d/1n_7nZIi5QtN9URzsKdFW6WtSxPM9uUK3QhQSbzbltHg
*
* @OnlyCurrentDoc
*/
function myExclusiveFunction() {
const t1 = new Date();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const exclusiveMode = ss.getActiveSheet().getRange('A4').getValue();
const lock = LockService.getDocumentLock();
if (!exclusiveMode || lock.tryLock(0)) {
// Lock acquired or not in exclusive mode
ss.appendRow([t1.toLocaleTimeString(), '', '▶️ Start']);
// Task to perform: just go idle for 3 seconds
Utilities.sleep(3000);
ss.appendRow([new Date().toLocaleTimeString(), '', `⏹️ [${t1.toLocaleTimeString()}] Finished`]);
if (exclusiveMode) {
lock.releaseLock();
}
} else {
ss.appendRow([t1.toLocaleTimeString(), '', '🛑 Execution aborted, lock active']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment