【发布时间】:2016-05-24 05:50:57
【问题描述】:
我创建了一个带有电子邮件字段的谷歌表单。响应存储在电子表格中。在提交时,我从工作表中取出最后一行(最新回复)并向该用户发送电子邮件。
我已经尝试实现一个锁定系统,但是它也不能按照我想要的方式工作。如果快速连续多次提交(即一分钟内 3 次),只有最后一个用户会收到一封发送给他们的电子邮件,他们实际上会收到 3 封重复的电子邮件,与快速连续提交的数量相同。
function EmailFormConfirmation() {
// Get a public lock on this script, because we're about to modify a shared resource.
var lock = LockService.getScriptLock()
// Wait for up to 30 seconds for other processes to finish.
lock.waitLock(30000);
try {
var sheetname = "reg-responses"
var columnnumber = 4
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetname);
// Determines row number of most recent form submission and sets it as "lastrow"
if (sheet.getRange(sheet.getMaxRows(),1).getValue() != "") {
var lastrow = sheet.getMaxRows()
}
else {
var count = 0
for (var i = 0; i < sheet.getMaxRows(); i++) {
if (sheet.getRange(sheet.getMaxRows()-i,1).getValue() != "") {
var lastrow = sheet.getMaxRows()-i
break;
}
}
}
var email = sheet.getRange(lastrow,columnnumber).getValue();
var name = sheet.getRange(lastrow,2).getValue();
var message = "<HTML><BODY>"
+"<h3>Your registration has been submitted</h3>"
+"<p><b>Name</b>: "+name+"</p>"
+"</HTML></BODY>";
//validation is handled on the form as regex
MailApp.sendEmail(email, "Form Submitted", "", {htmlBody: message});
//flags it as email sent
sheet.getRange(lastrow,8,1,1).setValue("Email Sent");
//Here is the catch if the lock doesn't work
if(!lock.hasLock()){
Logger.log('Could not obtain lock after 30 seconds.');
}
//Secondary catch for the entire function.
} catch (e) {
Logger.log(e.toString());
}
// Release the lock so that other processes can continue.
lock.releaseLock();
}
我必须在我的锁上解决什么问题才能解决这个问题?
【问题讨论】:
-
您正在获取活动电子表格,这意味着“提交表单”触发器已安装在电子表格中,而不是安装在表单中。指定为“提交表单”触发器的函数可以接收值对象。通常,该对象被分配名为“e”的变量。见以下链接:Apps Script Documentation - Event Objects - Sheets可以从事件对象中获取当前的Form提交值,比从sheet中获取要好。
-
正如您的经验所证明的那样,锁定服务并没有像大多数人认为的那样完成。这是个问题。在某些情况下,Lock Service 基本上是没用的。我没有解决办法。如果 Google 能解决这个问题,那就太好了。
-
嗯,lockService 工作正常。锁的具体问题是什么?
标签: javascript google-apps-script google-sheets google-forms