1

I've been facing an extrange issue with google scripts. Bellow the easy-to-understand snippet:

//https://stackoverflow.com/a/7390612/2873381
function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function run(working_day){
  if (!working_day){
     working_day = new Date();
  }
  console.log("working_day");
  console.log(typeOf(working_day));
  console.log(working_day);
  var timeZone   = Session.getTimeZone();
  var curr_day   = Utilities.formatDate(working_day, timeZone, "F");
  var curr_hour  = Utilities.formatDate(working_day, timeZone, "H");
  console.log(curr_day);
  console.log(curr_hour);
}

This snippet get now if no working_day is provided. Once it has a valid instance of Date it tries to get week-day and current-hour using Utilities handy functions.
If I run this snippet manually from Editor, there's no problem, output is the expected . ok
However, If I set a crontab execution, say every hour, this code raises an error ko
The weirdest point here is the unexpected javaobject value, I don't know why working_day gets this instance type....
Can you help me? Thanks

xecgr
  • 5,095
  • 3
  • 19
  • 28
  • 2
    When you began using the time based triggers your parameter was filled with the event object. – Cooper Jul 13 '19 at 17:22
  • Thanks you pointed exactly the clue! I've added a simple if checking the type allowing the script to know if its an scheduled run or manual one. ```//time-triggered execution if (typeOf(working_day)=="javaobject"){ working_day = getNow(); }``` Are there any more-elegant solution? – xecgr Jul 14 '19 at 07:34
  • Just use `working_day = new Date();`? – TheMaster Jul 14 '19 at 16:06

1 Answers1

2

Presumably your function run() calls some other function which requires the timezone, current day of the week and current hour. In this situation because of the way the trigger reports day-of-week I'd probably just avoid using the event object altogether and do it this way.

function run(){
  var dt=new Date();
  var timeZone   = Session.getScriptTimeZone();
  var curr_day   = dt.getDay();//0=Sunday 6=Saturday 
  var curr_hour  = dt.getHours();0-23
  Logger.log('%s,%s,%s',timeZone,curr_day,curr_hour);
}

And so it will run the same way whether is triggered via a timer based trigger or if you run it manually. It will take a little longer but not that much.

Cooper
  • 59,616
  • 6
  • 23
  • 54