Real-life problem is that I want to call api every X seconds and can't seem to accomplish it using Google scripts.
As I know you can call trigger in every 1, 5, 10, 15 or 30 minutes. Is there a way to run Google script every second?
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();
You could use the method after(durationMilliseconds) to call your function after a specified number of milliseconds, if you create the trigger at the end of your function, like this:
function myFunction() {
Logger.log("Logging");
ScriptApp.newTrigger("myFunction")
.timeBased()
.after(1000 * X) // Fire "myFunction" after X seconds
.create();
}
But it seems this method (at least currently) cannot be used for firing a function after much less than a minute, as you can see in this Issue Tracker case.
Apart from this, there is no time-based trigger that can be used for your purpose.
Another option, if you just want to perform some actions after X seconds, would be to use Utilities.sleep(milliseconds) and a for loop.
Of course, you would eventually reach Apps Script execution time limit, and for this reason you should:
after(durationMilliseconds).It could be something similar to this:
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();
}
This way, you can keep your desired frecuency most of the time, and only when the execution time limit is reached (every 6 or every 30 minutes, depending on your account) this frecuency will once be lower (around 1 minute), before going back to the desired frecuency. It's not the behaviour you expect, but I think it's the closest you can get to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With