Home > OS >  Lock Service when using UrlFetchApp to write to Google spreadsheet
Lock Service when using UrlFetchApp to write to Google spreadsheet

Time:03-22

I've not found SO posts on this issue. I'm not clear what role Lock Service has when writing to spreadsheet with UrlFetchApp.

I am asking about preventing a problem--not about a problem that currently is occurring (and which I don't know how to adequately simulate). Should Lock Service be used with UrlFetchApp "put" method for writing to a Google spreadsheet to prevent overwriting by near-concurrent users of the same script? And, if so, is the basic code grammar correct as outlined below?

Secondary question: I see no option with UrlFetch for a "SpreadsheetApp.flush()"-type command to apply all pending spreadsheet changes before releasing the lock. Does UrlFetchApp ensure all sheet changes are completed before returning?

Again, there is not now a problem writing to the spreadsheet using UrlFetchApp--the question is about preventing loss or overwriting of data with near-concurrent execution of the code.

 var lock = LockService.getScriptLock();
       try {
         lock.waitLock(15000); // wait 15 seconds for others' use of the code section and 
           lock to stop and then proceed
       } catch (e) {
           Logger.log('Could not obtain lock after 15 seconds.');
           return "Error: Server busy try again later."
       }
  var url= `https://sheets.googleapis.com/v4/spreadsheets/${ssID}/values/${postRange}?valueInputOption=RAW`;
    var options = {
        muteHttpExceptions: true,
        contentType: 'application/json',
        method:   'put',    
        payload: JSON.stringify(data), data
        headers: { Authorization: 'Bearer '   clientToken }
        };
   var response= UrlFetchApp.fetch(url,options); 
 lock.releaseLock();
// END - end lock here

CodePudding user response:

  • The use of LockService itself seems to be fine for your code. You could also consider using tryLock instead of waitLock, as you prefer.
  • If you don't have a specific reason to do otherwise, I'd suggest using the Spreadsheet Service or the Advanced Sheets Service instead of using UrlFetchApp. It would simplify your code.
  • When UrlFetchApp returns, the API request has been completed. All sheet changes should have been made by then. flush only makes sense in the context of the Apps Script service if you want to use updated data in the same script that made the update, since a script might not apply spreadsheet changes until the end of it.
  • Related