Prevent Google Scripts from Exceeding the Maximum Execution Time Limit

P
Published in: Google Apps Script

Google Apps scripts can run for a maximum period of 4-5 minutes and you’ll get the error “Exceeded maximum execution time” if the script takes more than the allowed time to complete.

The Save Gmail Attachments and Extract Gmail Addresses scripts fetch 50 Gmail threads in a single batch and processes the messages one by one. If any particular thread is long, the overall execution time may exceed the limit and the script may throw an exception.

To prevent the error from happening, inside the loop, we can keep a track of time since the script is running and elegantly stop when it is nearing the time limit.

function isTimeUp_(start) {
  var now = new Date();
  return now.getTime() - start.getTime() > 300000; // 5 minutes
}

function myFunction() {

  var threads = GmailApp.getInboxThreads(0, 50);
  var start = new Date();

  for (var t in threads) {
    if (isTimeUp_(start)) {
      Logger.log("Time up");
      break;
    }
    // Process the thread otherwise
    var messages = threads[t].getMessages();
  }
}
Published in: Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch