Created
July 14, 2023 10:23
-
-
Save phillypb/f9072288952f4996f6f1c5136724a9df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Lock Service - lock code to prevent overwriting data (concurrency). | |
* https://developers.google.com/apps-script/reference/lock | |
*/ | |
function onFormSubmit(e) { | |
// get lock that prevents any user from concurrently running a section of code. | |
var lock = LockService.getScriptLock(); | |
Logger.log("Initial ScriptLock is: " + lock); | |
// attempt to acquire the lock, timing out after the provided number of milliseconds if it's being used elsewhere. | |
lock.tryLock(10000); // 10 seconds | |
// check if can access the lock - returns Boolean | |
if (lock.hasLock()) { | |
// we have the lock so we can run our code that we do not want running concurrently | |
Logger.log("The lock is available"); | |
// get Form data | |
var formValues = e.namedValues; | |
// get specific values from Form ****************** | |
var emailAddress = formValues["Email address"][0]; | |
var name = formValues["What is your name?"][0]; | |
var question = formValues["What is your question?"][0]; | |
// get specific values from Form ****************** | |
// introduce a 3 second pause so we can test overlapping Form submissions and hence the lock | |
Utilities.sleep(3000); | |
// get collate Sheet | |
var collateSheet = SpreadsheetApp.openById("YOUR GOOGLE SHEET ID HERE"); | |
var activeSheet = collateSheet.getActiveSheet(); | |
// append Form data | |
var currentDate = new Date(); | |
var formData = [emailAddress, name, question, currentDate]; | |
activeSheet.appendRow(formData); | |
Logger.log("Form data successfully appended"); | |
// release lock so others can use the code | |
lock.releaseLock(); | |
Logger.log("Lock has been released"); | |
} else { | |
// failed to get the lock | |
Logger.log("The lock is NOT available"); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment