x-x*_*x-x 4 google-sheets google-apps-script
我在 Google Sheets 电子表格中有一个 Google App Script 函数,我需要使用时间驱动的触发器每天调用一次。
此函数的运行时间通常比脚本允许的最大时间(当前为 6 分钟)要长,因此我编写了它来通过多次调用来完成其工作。如果该函数尚未完成,我想创建一个临时的时间驱动触发器以在一分钟内再次运行该函数,并在调用该函数时删除临时触发器,但保持每日触发器处于活动状态。伪代码可能会更好地解释它......
function run_job_via_trigger(trigger) {
if(trigger === temporary trigger) {
// If this is a 'temporary' trigger that was created to
// run the job after the first call then delete it.
// This must not delete the daily trigger that makes the
// first call to the function.
// If I check the UID of the trigger here I still
// would need to know which trigger is the daily trigger
// and which is a temporary trigger!
ScriptApp.deleteTrigger(trigger)
}
const job_finished = job_that_takes_several_calls_to_complete();
if(job_finished === false) {
// Create a temporary time-driven trigger to call this
// function again in 1 minute.
ScriptApp.newTrigger('run_job_via_trigger').timeBased().everyMinutes(1).create();
}
}
function job_that_takes_several_calls_to_complete() {
// This function often takes more time to complete than
// the maximum time allowed for scripts to run. It keeps
// track of its execution time and returns true if it has
// finished doing what it needs to do or false if it
// needs more time and should be called again.
return finished ? true : false;
}
Run Code Online (Sandbox Code Playgroud)
如何检测哪个时间驱动触发器调用了该run_job_via_trigger函数,以便我可以删除临时触发器而不是每日触发器?
该电子表格还有其他几个时间驱动的触发器,因此据我所知,简单地在最后删除所有触发器并创建新的每日触发器并不是一个可接受的解决方案。
当使用触发器调用您的函数时,它会接收触发事件作为其参数。例如,您可以检查触发器 UID,如下所示:
function doWhatever(e) {
if(e.triggerUid === 'trigger_id') {
// do something
} else {
// do something else
}
}
Run Code Online (Sandbox Code Playgroud)
更新
有几种方法可以了解哪些触发器正在运行。
最好的情况是,当您创建触发器时,您将其 ID 存储在某处,例如用户属性,然后您始终知道它何时运行。但我猜你还没有这样做。
在您的情况下,您可能想做一些手动工作。转到触发器页面,找到您的重复触发器,单击右侧的三个点并选择“执行”。然后您将在过滤器中看到触发器 ID:
现在,您可以在代码中使用它来检查它是重复触发器还是临时触发器。