在 Google Apps 脚本中锁定同步修改一个电子表格的多个独立脚本

问题描述 投票:0回答:0

我有一个由两个或多个独立 Apps 脚本文件中的代码修改的电子表格。我需要一把锁,使我能够从所有这些 Apps 脚本文件中同步代码。

从使用任意对象的类 Java 锁定的角度考虑,使用被修改的电子表格的对象进行锁定就足够了。

LockService 类似乎缺少该选项,因为只有这三个:

getDocumentLock() Gets a lock that prevents any user of the current document from concurrently running a section of code.
这个看起来很接近,但是它锁定了“当前”文档,这对于独立脚本没有意义,并且不允许指定任意文档。

getScriptLock() Gets a lock that prevents any user from concurrently running a section of code.
多个脚本文件正在运行自己的代码,所以这也无济于事。

getUserLock() Gets a lock that prevents the current user from concurrently running a section of code.
在最坏的情况下,这可能会被使用,但它只解决了所有脚本都由同一用户运行的特殊情况。另一件事是,它导致需要更精细的“子锁”的特殊共享存储,以防万一人们不想在所有关键部分的整个时间内只使用一个全局锁 - 这变得复杂和缓慢。

我尝试的是使用电子表格的专用单元格使用以下逻辑实现我自己的以下锁定机制,该单元格包含使用以下逻辑的信号量值,但它在实现和使用时容易出错,在锁定方面并不完全可靠,我认为考虑到额外的也很慢电子表格单元格的读写:

Script S1 (and similarly for scripts S2, S3, ...):
Read value of the cell A1
If A1 is empty write "S1" into A1, else start over
Flush the write
Wait for 5 seconds
Read value of A1
If the value is "S1" execute critical section, else start over
After executing the critical section erase contents of A1
Flush the erase

锁定同步由多个独立应用程序脚本修改的一个文档的最佳方法是什么?

multithreading google-apps-script google-sheets
© www.soinside.com 2019 - 2024. All rights reserved.