限制调用 onEdit 的频率

Limit the frequency of calls to onEdit

我使用脚本编辑器编写了一些脚本来自动执行一些 google spread-sheet 任务。 我想在用户与我的用户 sheets 交互后做一些事情,例如更新一些以 _.

开头的背景 sheets

我写了以下内容:

function onEdit(e){

  var range = e.range;
  if (e.source.getActiveSheet().getName()[0]!='_'){ 

//It is an user edit!  

  UpdateOtherHiddenTables()

  }

};

我的问题是 UpdateOtherHiddenTables() 需要很长时间,比如 2 分钟,并且它会在任何用户编辑时触发,所以它并不理想。 您如何确保在用户与 sheet 交互后调用 UpdateOtherHiddenTables(),但不会太频繁?

我会使用 Script properties in combination with a timed trigger。 on-Edit 触发器仅记录电子表格已被编辑的事实:

function recordEdit() {
  var sp = PropertiesService.getScriptProperties();
  sp.setProperty("edited", "yes");
}

此函数需要 运行 由 installable trigger,简单的 onEdit 不会提供修改脚本属性所需的权限。

UpdateOtherHiddenTables 函数设置为 运行 每 10 分钟,或每小时,或您想要的任何时间间隔。它检查是否需要刷新。

function UpdateOtherHiddenTables() {
  var sp = PropertiesService.getScriptProperties();
  if (sp.getProperty("edited") == "yes") {
    // update stuff
    sp.setProperty("edited", "no");
  }
}

顺便说一句:onEdit 仅由用户编辑触发。更改电子表格中值的脚本不会触发该触发器。

我使用字符串值而不是布尔值,因为 Properties 将所有内容都字符串化。存储 false 可以得到字符串 "false",这是真实的...