如何减少执行时间 - 电子邮件警报,可从库中安装 onOpen 触发器



我在一个名为on的库中有这段代码打开多个电子表格:

function emailAlerts() {
// sends email alert when accurate anchors is above treshold
var linksSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('links');
var Ssurl = SpreadsheetApp.getActiveSpreadsheet().getUrl();
var accuracyCellValue = linksSheet.getRange(3,4).getValue();
var customerCellValue = linksSheet.getRange(1,5).getValue();
var treshold = 15;
if (accuracyCellValue > treshold) {
var message = 'Attention! The accuracte anchors for the customer is ' + accuracyCellValue + '%, while the treshold is: ' + treshold + '%. Customer spreadsheet:' + Ssurl;
var subject = 'Accurate anchors alert for customer ' + customerCellValue;
MailApp.sendEmail('yaniv@mydomain.co.il','noreply@mydomain.co.il', subject, message);
}
}

这有效,但问题是电子表格在打开时大约需要 15 秒才能完成加载。

我真的需要减少执行时间以避免用户混淆。

我想将函数保留在库中,以便在需要时轻松实现对所有电子表格的更改。

我将很高兴听到任何想法。

谢谢!

附言同一个库中有一些onEdit触发器 - 所有这些都很快被执行。

代码运行缓慢的原因是因为它包含对外部服务器的多次调用,特别是对SpreadsheetAppMailApp的调用。这些电话非常耗时。如果需要这些调用,则很难显著加快代码速度。

  • 您可以通过最小化外部调用量来稍微加快代码速度 - 请参阅 Apps 脚本最佳实践。

例如,修改:

var linksSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('links');
var Ssurl = SpreadsheetApp.getActiveSpreadsheet().getUrl();

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var linksSheet = spreadsheet.getSheetByName('links');
var Ssurl = spreadsheet.getUrl();
  • 另一个优化点是将尽可能多的代码移动到if语句中,如果在条件不满足的情况下不需要执行此代码。

样本:

function emailAlerts() {
// sends email alert when accurate anchors is above treshold
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var linksSheet = spreadsheet.getSheetByName('links');
var accuracyCellValue = linksSheet.getRange(3,4).getValue();
var treshold = 15;
if (accuracyCellValue > treshold) {
var customerCellValue = linksSheet.getRange(1,5).getValue();
var Ssurl = spreadsheet.getUrl();
var message = 'Attention! The accuracte anchors for the customer is ' + accuracyCellValue + '%, while the treshold is: ' + treshold + '%. Customer spreadsheet:' + Ssurl;
var subject = 'Accurate anchors alert for customer ' + customerCellValue;
MailApp.sendEmail('yaniv@mydomain.co.il','noreply@mydomain.co.il', subject, message);
}
}
  • 不直接适用于您的情况,但以防您在另一种情况下需要它:如果您从相邻范围内检索值,则使用getValues()检索整个范围的值要快得多,而不是循环遍历单元格并使用getValues()单独检索每个单元格的值。

最新更新