concurrency - 访问电子表格时锁定脚本不起作用

标签 concurrency google-apps-script google-sheets-api

我的问题是如何保证并发访问时不丢失数据。

我已将脚本发布为网络应用程序。我想向 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/

相关文章:

Java 不稳定的并发性

google-apps-script - 选择单元格时触发函数

java - 如何使用 API 在 Google 电子表格范围内查找值(行号和列号)?

c - 光泽文件锁定,用于并发访问

C# Task.Run() 与 C++ std::async()

java - volatile 发布保证有多深?

google-apps-script - Google AppScript的GetValue()无法获取带有子域(something@mydomain.com.mx)的邮件

google-apps-script - 我可以使用 Google Visualization API 在应用程序脚本中查询电子表格吗?

google-apps-script - 如何在 Google 应用程序脚本中查找不属于我的文件

javascript - 在拆分中使用析取