Ben Lim
Ben Lim

Reputation: 21

How to limit google script execution time to 1 minute?

How do I set a time limit to end a function from running after 1 minute?

Situation: i have a script that runs every 5 mins every day. My scripts are exceeding the daily computing time limit of 3 hours.

So, I need to make a function that calls calls my functon A (very long so i won post it here), but only lets it run for 1 minute maximum, then ends.

I have searched extensively but all the other solutions work with loops. My functon that is causing the timeout however is not a loop kind of function. I dont mind the function not being successfully completing.

Upvotes: 2

Views: 2317

Answers (1)

Alan Wells
Alan Wells

Reputation: 31320

You either need a loop, executing short sections of code that only run for a few seconds at a time; or you'll need to add multiple lines of code that check the status every "so often".

To get the start time, you could use:

var startTime = Date.now(); //Get milliseconds from a date in past

As a test, you can run the following function, and then View the Logs:

function exampleCode() {

  var startTime = Date.now();
  Logger.log(startTime);

  Utilities.sleep(1000); //Stop the code for 1 second

  var timeNow = Date.now();
  Logger.log(timeNow);

  var elapsedTime = timeNow - startTime;
  Logger.log(elapsedTime);
};

Of course, you wouldn't want to ever re-assign the startTime. So put that at the top of your code, and don't ever re-calculate it.

To stop the code, at 1 minute, that's 60000 milliseconds

if (elapsedTime > 60000) {return}; //Quit after 1 minute

You could create a function to check the elapsed time:

function elapsedTime() {
  var timeNow = Date.now();     
  var elapsedTime = timeNow - startTime;
  if (elapsedTime > 60000) {return 'die'}; //return 'die' if longer than 1 minute
};

if (elapsedTime() === 'die') {return};//Quit after 1 minute

Upvotes: 2

Related Questions