完全同时在Google App脚本中进行多次提交 [英] Multiple submission at exact same time in Google App Script

查看:66
本文介绍了完全同时在Google App脚本中进行多次提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Google App脚本创建了一个表单,并在Google Spreadsheet中发送了所有数据.

I created a form using Google App Script and send all the data in Google Spreadsheet.

我的GS代码:

function doGet(e){
  return HtmlService.createTemplateFromFile("Form1");
}

我的html代码只是一个简单的输入标记,每当用户提交它时,它将在Google Spreadsheet中追加一行.

my html code just a simple input tag and whenever users submit it it will append row in Google Spreadsheet.

这是我的代码:

function executeProgram(agentSub){
  var ss = SpreadsheetApp.openByUrl(url);
  var sheet = ss.getSheetByName("Submission");

  var timeStamp = new Date();
  sheet.appendRow([timeStamp,name,age]);
}

如果只有一个人提交表格,则代码现在可以正常工作.但是,如果有2个人在同一时间提交,那么它只会创建1行而不是2行.看起来第二行与第一行重叠.但是,如果第二个人在第一个人之后提交了1秒,则代码运行良好(创建了2行).我在这里想念什么,以及如何解决?

Now the code working fine if there are only one people submit the form. But if 2 people submit it at the exact same time, it will only create 1 row instead of 2. Look like the second is overlapped with the first one. But if the second person submitted 1 second after the first person, the code running fine(created 2 row). What am I missing here, and how to solve it?

谢谢!

推荐答案

答案

锁定服务允许脚本阻止并发访问代码段.当您有多个用户或进程正在修改共享资源并希望防止冲突时,这很有用.

Answer

Lock Service allows scripts to 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.

Lock Service根据限制有三种不同的方法,在这种情况下,您需要使用

Lock Service has three different methods depending on the restrictions, in this case you need to use getScriptLock() to make sure that the code section cannot be executed simultaneously regardless of the identity of the user.

  • 使用先前的方法 var lock = LockService.getScriptLock();

定义 Lock 的开始,有两个不同的选项:

Define the start of your Lock, there are two different options:

  • tryLock(timeoutInMillis) returns false if the lock was not acquired, true otherwise.
  • waitLock(timeoutInMillis) throws an exception if the lock could not be acquired

使用Lock 的结尾="nofollow noreferrer"> releaseLock().它允许等待锁的其他进程继续.

Define the end of your Lock with releaseLock(). It allows other processes waiting on the lock to continue.

(可选检查): hasLock()返回false,如果

(optional check): hasLock() returns false if

  • 未获取锁
  • 从未调用
  • tryLock waitLock
  • 在获取锁之前超时
  • releaseLock()被称为
  • lock was not acquired
  • tryLock or waitLock were never called
  • timed out before the lock could be retrieved
  • releaseLock() was called

这篇关于完全同时在Google App脚本中进行多次提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆