On form submit trigger - scripting results from a Google Docs Form

六眼飞鱼酱① 提交于 2021-02-04 19:58:58

问题


I have a form that submits data which will require testing and manipulation once the new form data is appended to the spreadsheet. Therefore I hope to use an "On form submit" trigger to process the latest entry (new last line).

However before I get too deep into scripting for that trigger, I am curious to know if the "On form submit" trigger is reliable. For instance, does it trigger immediately? And what happens if 2 (or more) form submissions occur simultaneously (or near-simultaneously)? Will the script attached to that trigger process each form submission separately and sequentially? Ultimately my main concern is that an appended record will get skipped from testing if a previous script is still running while new records are being appended from a form submission.

The other alternative is a "Time-driven" trigger, although that would require testing all of the data and then manipulating the records that meet certain criteria. I'm not opposed to using that type of trigger, but it will require more complex scripting, as well as a different approach to the process.

Does anyone have success/horror stories relating to the "On form submit" trigger that they could share with me?


回答1:


See: Class Lock

A representation of a mutual-exclusion lock. This class allows scripts to make sure that only one instance of the script is executing a given section of code at a time. This 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. The following examples shows how to use a lock in a form submit handler.

// Generates a unique ticket number for every form submission.
 function onFormSubmit(e) {
   var targetCell = e.range.offset(0, e.range.getNumColumns(), 1, 1);

   // Get a public lock on this script, because we're about to modify a shared resource.
   var lock = LockService.getPublicLock();
   // 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);

   // Release the lock so that other processes can continue.
   lock.releaseLock();

   targetCell.setValue(ticketNumber);
 }

Without the LockService, if two users submit the form at approximately the same time the ticket numbers could end up the same, since the lastTicketNumber property could change after it was read from the ScriptProperties but before the new value was written back.

The above was copied from the new and improved documentation.



来源:https://stackoverflow.com/questions/16067997/on-form-submit-trigger-scripting-results-from-a-google-docs-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!