我的问题是如何保证并发访问时不丢失数据。
我已将脚本发布为网络应用程序。我想向 DATA_SHEET 添加新行。处理提交按钮的函数如下所示:
function onButtonSubmit(e) {
var app = UiApp.getActiveApplication();
var lock = LockService.getPublicLock();
while (! lock.tryLock(1000))
;
var ssheet = SpreadsheetApp.openById(SHEET_ID);
var sheet = ssheet.getSheetByName(DATA_SHEET);
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var rangeToInsert = sheet.getRange(lastRow+1, 1, 1, lastCol);
var statText = rangeToInsert.getA1Notation();
rangeToInsert.setValues(<some data from webapp form>);
app.getElementById('statusLabel').setText(statText);
lock.releaseLock();
return app;
}
但是好像这样不行。当我打开两个表单并在一秒钟内单击提交按钮时,它在 statsLabel 中显示相同的范围并将数据写入相同的范围。所以我丢失了一种形式的数据。
这段代码有什么问题?似乎 tryLock() 不会阻止脚本。
有没有其他方法可以防止对工作表的并发写访问?
最佳答案
可能值得一看 appendRow()
,而不是使用 getLastRow()
/setValues()
等
Allows for atomic appending of a row to a spreadsheet; can be used safely even when multiple instances of the script are running at the same time. Previously, one would have to call getLastRow(), then write to that row. But if two invocations of the script were running at the same time, they might both read the same value for getLastRow(), and then overwrite each other's values.
关于concurrency - 访问电子表格时锁定脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12808674/