如果需要,如何使用 LockService 正确等待另一个执行完成



我有一个表单/工作表的on form submit触发器。我想防止两次代码执行相互叠加。我知道我必须使用LockService但我不完全确定如何使用。而且我真的不知道如何正确测试我的代码/理论......

在 https://developers.google.com/apps-script/reference/lock/lock 的示例中,它只等待 30 秒的锁定。这似乎有风险,因为如果另一个执行时间超过 30 秒会发生什么?相反,我认为无限期等待另一个执行完成会更有意义。

到目前为止我的想法:

// get a script lock
var lock = LockService.getScriptLock();
// try to get a lock in 10 second intervals
// the probability that the form would be submitted twice
// at exactly the same time is very low
// so i'm not worried about waiting indefinitely in 10 second intervals
// if it can never get a lock the script will reach the script runtime quota and fail
// which will send me an email letting me know I need to manually rerun something
while (!lock.tryLock(10000)) { }
// do what i need to here
// release the lock
lock.releaseLock();

10 秒或总共 30 分钟的批次不会有什么区别。如果您选择等待 30 分钟,并且即将在 10 秒内锁定,那么您将在 10 秒内锁定。input 参数是在引发错误/返回之前等待的最大毫秒数,而不是最小值。

最新更新