Ray
Ray

Reputation: 189

"Exception: This script has too many triggers" when creating a time-based trigger

Hey I'm a beginner in Google Apps Script. I got an error:

Exception: This script has too many triggers.

Even though I only have 1 trigger which is:

ScriptApp.newTrigger("Status()").timeBased().atDate(2021, 2, 1).create();

I'm actually thinking about using more time-driven triggers but i tried 1 and it has this error. Do you have any idea what is happening?


When the Web App is launched, new triggers are always created. Is there any way to keep the triggers without creating another one when the Web App is visited?

Upvotes: 1

Views: 1723

Answers (1)

0Valt
0Valt

Reputation: 10355

Problem

Installing a new trigger each time a Web App is open.

Ensuring only one instance of a trigger is installed

The sample below is a utility for checking whether the installable trigger is already in place or needs to be installed. Configure it to your liking and run each time the Web App is open using doGet trigger.

/**
 * @summary gets or installs a trigger
 * @param {string} callbackName
 * @param {GoogleAppsScript.Script.EventType} type
 * @param {function} installer
 */
const getOrIntallTrigger = (callbackName, type, installer) =>

    /**
     * @returns {?GoogleAppsScript.Script.Trigger}
     */
    () => {

        console.log(`Checking for triggered ${callbackName} function`);

        const ss = SpreadsheetApp.getActiveSpreadsheet();

        const triggers = ScriptApp.getUserTriggers(ss);

        const found = triggers
            .filter(trigger => trigger.getEventType() === type && trigger.getHandlerFunction() === callbackName);

        const [trigger] = found;

        !trigger && installer();

        return trigger;
    };

Notes

  1. For this one to work, you need to have V8 runtime enabled and be comfortable with ES6 syntax.

Upvotes: 1

Related Questions