Document locks serialize everyone on a spreadsheet. User locks only serialize the same user's overlapping runs — handy for personal quotas, user-property writes, or add-ons where each account should not block others.
What you'll need
- A critical section that is per-user (not shared sheet state)
- Contrast with
withDocumentLockwhen contention is the bound spreadsheet
How to use this snippet
function withUserLock(fn, waitMs) {
waitMs = waitMs || 30000;
var lock = LockService.getUserLock();
if (!lock.tryLock(waitMs)) {
throw new Error('Could not acquire user lock within ' + waitMs + 'ms');
}
try {
return fn();
} finally {
lock.releaseLock();
}
}
function bumpPersonalCounter() {
return withUserLock(function () {
var props = PropertiesService.getUserProperties();
var n = Number(props.getProperty('runs') || '0') + 1;
props.setProperty('runs', String(n));
return n;
});
}
Tips:
- Same try/finally shape as document lock — don't skip
releaseLockon errors. - For project-wide contention in standalone scripts, use
LockService.getScriptLock()the same way.
Happy Coding!
