Munkey
Munkey

Reputation: 956

Can lockservice for GAS work across multiple functions in the same project

I had a problem with a script I wrote, the solution to the issue was lock service to avoid collisions with form submits. As I had no idea this would be an issue, I've had to go back and revisit old scripts.

I have script that has a few different functions, and it passes data from one function to another. Eventually it writes data to sheet, creates a PDF, can email it and stores the PDF to a folder in google drive.

Here's a brief example of what I mean

function firstFunction() {

  //Do stuff, return something
  return something;

  secondFunction(something);

}


function secondFunction(something) {

// Do stuff, return test

thirdFunction(test);

}





function thirdFunction(test) {

// Do stuff, return that

return that;

fourthFunction(that);

}

function fourthFunction(that){


// finish doing stuff. Write data


}

I also have a separate script, that would invoke the first and iterate through a list of data, to bulk produce PDFs.

I'm worried that if 2 people invoke the script at the same time, I'll have issues again.

Given the example script I've given, Do I have to use LockService on each function? Or can I declare the lock in the first function and release it in the last.

I'm also curious on how it would sit with the 2nd script that invokes the first several times. Would adding the lock service in this one be sufficient, or would I also have to add it to the second too?

Thanks in advance.

EDIT BELOW

I just remembered I posted the real code on Code Review for advice, and boy did I get some!! Code Review Post

Upvotes: 1

Views: 507

Answers (1)

David Tew
David Tew

Reputation: 1471

I should think that you don't need Lock Service in this case at all.

In the Lock Service documentation it states:
[Lock Service] Prevents concurrent access to sections of code. This can be useful when you have multiple users or processes modifying a shared resource and want to prevent collisions. (documentation: https://developers.google.com/apps-script/reference/lock/lock-service#getScriptLock%28%29) or [Class Lock] is particularly useful for callbacks and triggers, where a user action may cause changes to a shared resource and you want to ensure that aren't collisions. (documentation: https://developers.google.com/apps-script/reference/lock/lock#tryLock%28Integer%29)

Now, having read the script code that you link to in your edit, I saw no shared resources that the script is writing to. So I conclude no lock is required. (EDIT: On second reading, I see that the script is writing to a sheet once, the shared resource. So your lock can go within that function only.)

I will cross post this point to Google Apps Script Plus community https://plus.google.com/communities/102471985047225101769 since there are experts there who can confirm.

Upvotes: 2

Related Questions