Is there a difference in how Google Apps Script is interpreted when run as a Time-Driven script and when run from the Editor?
I have a Google Apps Script function which seems to be interpreted differently when run from the editor, and when run in a Time-Driven script. When run as a scheduled script, it returns the following error and I frankly do not understand why. Error Exception: Invalid argument: yyyy-MM-dd'T'[object Object]:00Z at isBetweenTimeWithTz(Code:24:24)
When the function is run from the editor, I get the output i would expect, e.g. 0 '2022-01-13T00:50:00+0100' '2022-01-13T01:30:00+0100' Wed Jan 12 2022 18:50:00 GMT-0500 (Eastern Standard Time) Wed Jan 12 2022 19:30:00 GMT-0500 (Eastern Standard Time).
function isBetweenTimeWithTz(from_t="00:50", to_t="01:30", tz="Europe/Prague"){
now = new Date();
from_str = Utilities.formatDate(now, tz, `yyyy-MM-dd'T'${from_t}:00Z`);
to_str = Utilities.formatDate(now, tz, `yyyy-MM-dd'T'${to_t}:00Z`);
from_dt = new Date(from_str);
to_dt = new Date(to_str);
is_between = from_dt <= now & now <= to_dt;
console.log(is_between, from_str, to_str, from_dt, to_dt);
return is_between;
}
For scheduling, I use this function:
function createTimeDrivenTriggers() {
ScriptApp.newTrigger('isBetweenTimeWithTz')
.timeBased()
.everyMinutes(1)
.create();
console.log("Trigger triggered");
}
The difference I noticed when I printed the parameters is that, the first parameter in the time-driven script was overwritten with this:
{authMode=FULL, second=3.0, triggerUid=2100292014431267688, minute=24.0, timezone=UTC, hour=16.0, day-of-month=13.0, day-of-week=4.0, week-of-year=2.0, month=1.0, year=2022.0}
To avoid the first parameter being overwritten, you can add a placeholder parameter that will contain the above value.
Modification:
function isBetweenTimeWithTz(placeholder="", from_t="00:50", to_t="01:30", tz="Europe/Prague"){
Output:
All triggered functions are passed an event
parameter, as documented here:
When a trigger fires, Apps Script passes the function an event object as an argument, typically called
e
It's sometimes useful to use the data from that parameter within the trigger execution. The event object for a timed trigger contains data about the time at which the trigger was launched.