Learn How to Suspend a Google Script to Avoid Limits

Advertisements

Hello, Guys welcome back Here Learn How to Suspend a Google Script to Avoid Limits. Google Script puts restrictions on several services. If your script exceeds the defined quota, an exception is thrown and execution is halted until the quota is reset.

A Google Script, for example, may read 20,000 email messages from Gmail in 24 hours before throwing an error such as Service called too many times.

The Save Gmail extension collects email messages from Gmail and saves them to your Google Drive as PDF files. It runs the script in the background using a timer, or the user may start the programme directly to retrieve emails. Also Learn How to Get Hidden and Filtered Rows in Google Sheets with Google Script easily

Advertisements

If a user’s Gmail account has a high amount of emails and they attempt to execute the script too frequently, the quota may be exceeded and the trigger may fail. It is thus beneficial to include checks in the script that will temporarily halt script execution if a known exception is thrown.

const suspend = (timeInMinutes = 60) => {
  CacheService.getScriptCache().put('SUSPEND', Date.now(), timeInMinutes * 60);
};

const isSuspended = () => {
  return CacheService.getScriptCache().get('SUSPEND');
};

To determine if a script has been suspended, we use Google Script’s CacheService.

The expiry period is set to 60 minutes, thus the script will restart execution automatically after the cache value has expired.

Advertisements

We include a try catch block in the main programme that parses the exception message. We suspend the script for 60 minutes if the message fits one of the known faults, such as Service taking too much computer time in one day or Service being invoked too many times.

const app = () => {
  try {
    // download emails
  } catch ({ message }) {
    if (/Service invoked too many times/.test(message)) {
      suspend(60);
    }
  }
};

const hourlyTrigger = () => {
  if (!isSuspended()) {
    app();
  }
};

When our hourlyTrigger is called again, it will only launch the main app if the Google Script is not suspended. Because we’re utilising the Cache Service here, when the cache expires, the suspended status is immediately reset.

Advertisements

Leave a Comment