Script runtime execution time limit

One thing you could do (this of course depends on what you are trying to accomplish) is:

  1. Store the necessary information (i.e. like a loop counter) in a spreadsheet or another permanent store(i.e. ScriptProperties).
  2. Have your script terminate every five minutes or so.
  3. Set up a time driven trigger to run the script every five minutes(or create a trigger programmatically using the Script service).
  4. On each run read the saved data from the permanent store you’ve used and continue to run the script from where it left off.

This is not a one-size-fit-all solution, if you post your code people would be able to better assist you.

Here is a simplified code excerpt from a script that I use every day:

function runMe() {
  var startTime= (new Date()).getTime();
  
  //do some work here
  
  var scriptProperties = PropertiesService.getScriptProperties();
  var startRow= scriptProperties.getProperty('start_row');
  for(var ii = startRow; ii <= size; ii++) {
    var currTime = (new Date()).getTime();
    if(currTime - startTime >= MAX_RUNNING_TIME) {
      scriptProperties.setProperty("start_row", ii);
      ScriptApp.newTrigger("runMe")
               .timeBased()
               .at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
               .create();
      break;
    } else {
      doSomeWork();
    }
  }
  
  //do some more work here
  
}

NOTE#1: The variable REASONABLE_TIME_TO_WAIT should be large enough for the new trigger to fire. (I set it to 5 minutes but I think it could be less than that).

NOTE#2: doSomeWork() must be a function that executes relatively quick( I would say less than 1 minute ).

NOTE#3 : Google has deprecated Script Properties, and introduced Properties Service in its stead. The function has been modified accordingly.

NOTE#4: 2nd time when the function is called, it takes the ith value of for loop as a string. so you have to convert it into an integer

Leave a Comment