Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
J. Aginuz Avatar asked Mar 02 '26 05:03

J. Aginuz


1 Answers

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();
like image 103
Kate Avatar answered Mar 04 '26 03:03

Kate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!