Reputation: 5839
I've got an on form submit
trigger for a Form/Sheet. I want to prevent two executions of code stepping on top of each other. I know I have to use LockService
but I'm not entirely sure how. And I don't really know how to properly test my code/theory...
In the example at https://developers.google.com/apps-script/reference/lock/lock, it just waits 30 seconds for a lock. This seems risky because what happens if the other execution takes longer than 30 seconds? Instead, I think it would make more sense to wait indefinitely for the other execution to finish.
My thoughts so far:
// get a script lock
var lock = LockService.getScriptLock();
// try to get a lock in 10 second intervals
// the probability that the form would be submitted twice
// at exactly the same time is very low
// so i'm not worried about waiting indefinitely in 10 second intervals
// if it can never get a lock the script will reach the script runtime quota and fail
// which will send me an email letting me know I need to manually rerun something
while (!lock.tryLock(10000)) { }
// do what i need to here
// release the lock
lock.releaseLock();
Upvotes: 1
Views: 341
Reputation: 50855
Batches of 10 seconds or a total of 30 minutes wouldn't make a difference. If you chose to wait for 30 minutes and you are about to get a lock in 10 seconds, you'll get a lock in 10 seconds. The input argument is the maximum number of milliseconds to wait before throwing a error/returning and not the minimum.
Upvotes: 2