I'm using LockService for a script that locates the active row and a couple of criteria and ifthey match, then an email is sent.
However, I'm seeing Service invoked too many times more frequently that I thought I'd see, so I'm not sure I'm using it correctly.
Is getting the lock only after the criteria are met better down the road, instead of making it unavailble even when "that run" doesn't meet the criteria?
It's got an installable trigger set on edit basis, so I'm escaping it as soon as possible before getting the lock, but still...
Here's the code:
function sendEmail() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
if (sheet.getName() != 'Todays Tests V2') {
return;
}
const lock = LockService.getScriptLock();
try {
lock.waitLock(3000); // wait 03 seconds for others' use of the code section and lock to stop and then proceed
} catch (e) {
Logger.log('Could not obtain lock after 03 seconds.');
return HtmlService.createHtmlOutput("<b> Server Busy. Please try after some time <p>");
}
const testSheet = ss.getSheetByName("Todays Tests V2");
const row = sheet.getActiveCell().getRow();
const col = sheet.getActiveCell().getColumn();
const emailSent = testSheet.getRange(row, 14, 1, 1).getValue();
const sendResults = testSheet.getRange(row, 15, 1, 1).getValue();
const formRespSheet = ss.getSheetByName('Form Responses 1');
const formRespRng = formRespSheet.getRange(2, 13, formRespSheet.getLastRow() - 1, 2);
const formRespValues = formRespRng.getValues();
if (ss.getActiveSheet().getSheetName() == testSheet.getSheetName()
&& row > 5
&& col == 15
&& sendResults == true) {
const email = testSheet.getRange(row, 5).getValue();
const name = testSheet.getRange(row, 3).getValue() + ' ' + testSheet.getRange(row, 4).getValue();
const testNo = testSheet.getRange(row, 2).getValue();
GmailApp.sendEmail(email, "Subject", name + " Msg.", { name: 'Custom Senders Name' });
for (var n = 0; n < formRespValues.length; n++) {
if (formRespValues[n][1] == testNo) {
formRespSheet.getRange('M' + (2 + n)).setValue('Yes');
}
}
}
lock.releaseLock();
}
I'd love to understand how this can be improved.
Thank you!