gpt4 book ai didi

javascript - GetScriptLock 似乎不起作用

转载 作者:行者123 更新时间:2023-11-30 16:06:26 24 4
gpt4 key购买 nike

我试图在提交表单时生成一个唯一编号。我已将我的脚本简化为以下内容以进行测试。

function onFormSubmit(event) {

// Get a script lock, because we're about to modify a shared resource.
var lock = LockService.getScriptLock();

// Wait for up to 30 seconds for other processes to finish.
lock.waitLock(30000);

var ticketNumber = Number(ScriptProperties.getProperty('lastTicketNumber')) + 1;
ScriptProperties.setProperty('lastTicketNumber', ticketNumber);

targetCell = event.range.offset(0, event.range.getNumColumns(), 1, 1);
targetCell.setValue(ticketNumber);

SpreadsheetApp.flush();

// Release the lock so that other processes can continue.
lock.releaseLock();

};

我发现如果我在一秒钟内提交两个表单,我会得到相同的票号。

如有任何帮助,我们将不胜感激。

最佳答案

前言:您正在使用已弃用的 ScriptProperties服务,这已被 Properties Service 取代.您可能想先更改它。

过去,我在尝试快速连续地使用项目属性时收到了相同的结果。这几乎就像旧值在脚本属性使用的任何缓存应用程序脚本中停留了几秒钟。

我建议使用 Cache Service以补充需要立即反射(reflect)更改的脚本。

修改后的代码:

function onFormSubmit(event) {

// Get a script lock, because we're about to modify a shared resource.
var lock = LockService.getScriptLock();

// Wait for up to 30 seconds for other processes to finish.
lock.waitLock(30000);

var scriptCache = CacheService.getScriptCache();
var scriptProperties = PropertiesService.getScriptProperties();

var cachedTicketNumber = scriptCache.get('lastTicketNumber');
var ticketNumber;

if(cachedTicketNumber !== null){
ticketNumber = Number(cachedTicketNumber) + 1;
} else {

//Cache has expired/does not exist, fall back to properties service
ticketNumber = Number(scriptProperties.getProperty('lastTicketNumber')) + 1;
}

//Set properties service, and cache values of the ticket number
scriptProperties.setProperty('lastTicketNumber', ticketNumber);
scriptCache.put('lastTicketNumber', ticketNumber, 21600); //21600 seconds = 6 hours, if you want it to last that long

targetCell = event.range.offset(0, event.range.getNumColumns(), 1, 1);
targetCell.setValue(ticketNumber);

SpreadsheetApp.flush();

// Release the lock so that other processes can continue.
lock.releaseLock();

};

关于javascript - GetScriptLock 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972691/

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