gpt4 book ai didi

google-apps-script - 如何防止多个用户在 Google 表格中同时运行 Google Apps 脚本代码?

转载 作者:行者123 更新时间:2023-12-05 05:09:21 25 4
gpt4 key购买 nike

我正在向多个用户共享一个 google 脚本表,我只是想防止同一用户同时运行该脚本。我需要做什么?是通过代码还是仅通过设置?

最佳答案

正如@TheMaster 在评论中所说,LockService 是必经之路。具体来说,你想要 LockService.getDocumentLock()LockService.getScriptLock()取决于脚本的设置方式。

如何在 Apps 脚本中使用锁定服务的示例:

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

关于google-apps-script - 如何防止多个用户在 Google 表格中同时运行 Google Apps 脚本代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57627204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com