首页 > 解决方案 > 谷歌应用脚​​本tryLock/waitLock超时限制累积后续网络应用调用?

问题描述

我一直在尝试调试一个问题,即我正在使用 GAS 将多个新行(通过多个 HTTP GET)写入谷歌电子表格,但在写入其中一些后,它们似乎未能获得锁定。我最初的超时时间为 5000 毫秒(5 秒),这对于一次调用来说应该有足够的时间,但我注意到如果我要添加 20 行,那么超时会导致随机行更新失败。当我将时间移至 30 秒时,20 行工作正常。但是如果我排到 60 行,我又会随机失败。移动到 60 秒超时似乎在那里工作。

看起来这个超时实际上需要考虑写出所有行所需的累积时间。我想得越多,我认为这是有道理的,因为我是通过异步方法从 Flutter/Web 项目中进行这些调用的。下面的 dart 代码用于 HTTP GET...

  void submitOrder(String orderParms) async {
    try {
      String fullURL = "$URL$orderParms";
      await http.get(fullURL).then((response) {
        callback(convert.jsonDecode(response.body)['status']);
      });
    } catch (e) {
      print(e);
    }
  }

下面的 GAS doGet 方法...

function doGet(request){
  var prodID = "1qNt0Q-not-K37U-the-Ea8Fa-real-ynUF-url-xwskYfmDgnMEw2lX_LFblSuDw"; 
  var result = {"status": "SUCCESS"};
  try {
    // Get all Parameters
    var lastName   = request.parameter.lastName;
    var firstName  = request.parameter.firstName;
    var lock = LockService.getUserLock();  
    if (lock.tryLock(60000)) {     // currently using 60 sec to be safe??
      // Open the correct sheetGoogle Sheet using ID
      var sheet_prod = SpreadsheetApp.openById(prodID);
      var rowData    = sheet_prod.appendRow([lastName, firstName]);
      // Need to flush these updates so they fully take before releasing the lock
      SpreadsheetApp.flush();
      // ok, done important spreadsheet stuff, release the lock
      lock.releaseLock();
    // else did not get a lock
    } else {
      result = {"status": "FAILED - No Lock!", "message": "Lock timed out"};      
    }
  } catch(exc){
    result = {"status": "Exception! FAILED", "message": exc.message};
  }
  // Return result
  return ContentService
  .createTextOutput(JSON.stringify(result))
  .setMimeType(ContentService.MimeType.JSON);  
}

我目前将超时设置为 60 秒,以确保我可以处理 30-40 行,而不会失败获得锁。将超时设置这么高有什么害处吗?任何见解都非常感谢!

标签: google-apps-scriptgoogle-sheetstimeoutlocking

解决方案


官方文档没有提到使用“大”数字的任何“危害”,因此milliseconds这完全取决于这是否会影响您的网络应用程序的目的和/或电子表格的目的。

旁注:由于您的代码在发布文档后不会对电子表格进行任何更改,因此没有必要包含SpreadsheetApp.flush().


推荐阅读