Gug*_*dua 4 triggers google-apps-script
现实生活中的问题是,我想每 X 秒调用一次 api,但似乎无法使用 Google 脚本来完成它。
据我所知,您可以每隔 1、5、10、15 或 30 分钟调用一次触发器。有没有办法每秒运行 Google 脚本?
function createTimeDrivenTriggers() {
ScriptApp.newTrigger('myFunction')
.timeBased()
.everyMinutes(1) //I can not write 0.01 instead of 1 here.
.create();
}
function myFunction() {
Logger.log("Logging");
}
createTimeDrivenTriggers();
Run Code Online (Sandbox Code Playgroud)
如果您在函数末尾创建触发器,则可以使用after(durationMilliseconds)方法在指定的毫秒数后调用函数,如下所示:
function myFunction() {
Logger.log("Logging");
ScriptApp.newTrigger("myFunction")
.timeBased()
.after(1000 * X) // Fire "myFunction" after X seconds
.create();
}
Run Code Online (Sandbox Code Playgroud)
但似乎这种方法(至少目前)不能用于在不到一分钟后触发函数,正如您在问题跟踪器案例中看到的那样。
除此之外,没有任何基于时间的触发器可以用于您的目的。
如果您只想在 X 秒后执行一些操作,另一种选择是使用Utilities.sleep(milliseconds)和for
循环。
当然,您最终会达到 Apps 脚本执行时间限制,因此您应该:
after(durationMilliseconds)
.它可能类似于这样:
function myFunction() {
var numIterations = 10; // Number of iterations before reaching time limit (change accordingly)
for (var i = 0; i < numIterations; i++) {
// Your actions
Utilities.sleep(1000 * X); // Pause execution for X seconds
}
ScriptApp.newTrigger("myFunction")
.timeBased()
.after(1000 * Y) // Fire "myFunction" after Y seconds
.create();
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以在大部分时间保持您想要的频率,并且只有当达到执行时间限制时(每6分钟或每30分钟,取决于您的账户)这个频率才会降低一次(大约1分钟),然后再继续返回到所需的频率。这不是您期望的行为,但我认为这是您能达到的最接近的行为。