GetScriptLock似乎不起作用

时间:2016-05-01 22:26:13

标签: javascript google-apps-script

我正在尝试在提交表单时生成唯一编号。我已将我的脚本简化为以下测试。

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

};

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

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

前言:您使用的是已弃用的ScriptProperties服务,该服务已被Properties Service取代。你可能想先改变它。

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

我建议使用Cache Service来补充需要立即反映更改的脚本。

修改后的代码:

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

};