简体   繁体   中英

GetScriptLock does not seem to work

I am trying to generate a unique number when a form is submitted. I have simplified my script to the following for testing.

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

};

I find that if I submit two forms within a second of each other I get the same ticketnumber.

Any help would be appreciated.

Preface : You are using the deprecated ScriptProperties service, this has been replaced by the Properties Service . You probably want to change this first.

In the past I have received the same results when trying to utilize the project properties in rapid succession. It's almost as if the old value hangs around in whatever caching apps script uses for script properties for a few seconds.

I would recommend utilizing the Cache Service to suppliment for scripts that need to reflect changes immediately.

Modified Code:

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

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM