J. Aginuz
J. Aginuz

Reputation: 31

How do I prevent multiple users from running Google Apps script code at the same time in a Google Sheet?

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?

Upvotes: 3

Views: 1818

Answers (1)

Kate
Kate

Reputation: 1533

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();

Upvotes: 2

Related Questions