Create triggers programmatically using Apps Script

A trigger is a feature that lets you automatically run Apps Script functions on a recurring schedule or when specific events occur. For example, you can set up a time based trigger to run your function every morning or an event based trigger to run your function whenever a user edits your spreadsheet.

I've written a detailed tutorial on Triggers in Google Sheets. In that tutorial, I explain what triggers are in detail and when to use them. I also explain the difference between simple triggers and installable triggers in that tutorial.

In this tutorial, I will teach you how to create installable triggers programmatically (i.e., using code) instead of creating them via the Triggers page in the Apps Script code editor.

The objective of setting up a trigger is to run a function automatically. This means we need a function that will be run by the trigger. In this tutorial, I will assume that we want the trigger to run a function called runScript(). This function is simple and logs the event object that provides information about the event that caused the trigger to run the function.

function runScript(eventInfo) {
 Logger.log(JSON.stringify(eventInfo));
}

Prerequisites

This tutorial assumes that you're familiar with the concept of triggers in Apps Script. Please refer to the tutorial on Triggers in Google Sheets if you're not familiar with what triggers are.

Table of contents

Create time-based triggers using Apps Script

Use time-based triggers when you want to automatically run an Apps Script function on some recurring schedule or on some future date.

How to create triggers using Apps Script?

To create a trigger, first use ScriptApp.newTrigger("runScript") to create a trigger object that will run a function called runScript().

Then specify if you want the trigger to be Time based or Spreadsheet event based. Next configure your trigger and finally call the create() method to create the trigger.

function createTimeTriggerSpecifcDate() {
 //Create a trigger to run a function called "runScript"
 ScriptApp.newTrigger("runScript")
   //The trigger is time based
   .timeBased()
   //Configure when to run the trigger
   .at(new Date(2020, 2, 1))
   //Finally create the trigger
   .create();
}

Create a time-based trigger using Apps Script that will run a function on a specific date in the future

You can configure the trigger to run at a specific date in the future by either using the .at(<date>) method or by using the .atDate(<year>, <month>, <day>) method.

Both of these options have the same effect. In the first method, you need to create a Date object first and then use it. In the second method, you directly use the year, month and day to specify the date.

Option 1: .at()

function createTimeTriggerSpecifcDate() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .at(new Date(2020, 2, 1))
   .create();
}

Option 2: .atDate(, , )

function createTimeTriggerSpecifcDateMethod2() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .atDate(2021, 2, 1)
   .create();
}

Create a time-based trigger using Apps Script that will run a function once every N minutes

You can configure the trigger to run every N minutes using the .everyMinutes(N) method.

function createTimeTriggerEveryNMinutes() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .everyMinutes(N)
   .create();
}

Create a time-based trigger using Apps Script that will run a function once every N hours

You can configure the trigger to run every N hours using the .everyHours(N) method.

function createTimeTriggerEveryNHours() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .everyHours(N)
   .create();
}

Create a time-based trigger using Apps Script that will run a function once every N days

You can configure the trigger to run every N days using the .everyDays(N) method.

function createTimeTriggerEveryNDays() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .everyDays(N)
   .create();
}

Create a time-based trigger using Apps Script that will run a function once every N weeks

You can configure the trigger to run every N weeks using the .everyWeeks(N) method.

function createTimeTriggerEveryNWeeks() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .everyWeeks(N)
   .create();
}

Create a time-based trigger using Apps Script that will run a function at a certain time on a recurring schedule

There are two ways to make the trigger run at a specific time of the day on a recurring schedule. In the first option, you specify the approximate hour of the day and the frequency at which the trigger should be run (i.e, daily, weekly, etc.). The second option allows you to also specify the minute in addition to the hour.

Option 1: Specify the hour of the day when the script should be run and the recurring schedule (i.e. should the function be run daily, weekly etc.)

function createTimeTriggerAtSpecificHour() {
 ScriptApp.newTrigger("runScript")
   .timeBased()
   .atHour(4)
   .everyDays(2)
   .create();
}

Option 2: Specify the time of the day using hours and minutes and also specify the recurring schedule (i.e. should the function be run daily, weekly etc.)

function createTimeTriggerAtSpecificHourMinute() {
 ScriptApp.newTrigger("runScript1")
   .timeBased()
   .atHour(5)
   .nearMinute(15)
   .everyDays(2)
   .create();
}

Specify a timezone to override the default timezone when configuring a time based trigger

By default, the time you specify will be indexed to the timezone of the script. You can override this default by specifying the timezone using the inTimezone() method. You need to pass the timezone as a string parameter. Please refer to a full list of timezones and the corresponding strings to use at http://joda-time.sourceforge.net/timezones.html.

function specifyTimezone() {
 ScriptApp.newTrigger("runScript1")
   .timeBased()
   .atHour(5)
   .nearMinute(15)
   .everyDays(2)
   .inTimezone("America/Los_Angeles")
   .create();
}

Create Spreadsheet triggers using Apps Script

You can also configure triggers to run an Apps Script function when certain events occur in your Google Sheets spreadsheet.

Create an Open trigger using Apps Script

You can configure the trigger to run whenever your spreadsheet is opened by using the .onOpen() method. This approach is commonly used to create a custom menu when your spreadsheet is opened.

function createOpenTrigger() {
 ScriptApp.newTrigger("runScript")
   .forSpreadsheet(SpreadsheetApp.getActive())
   .onOpen()
   .create();
}

Create an Edit trigger using Apps Script

You can configure the trigger to run whenever your spreadsheet is edited by using the .onEdit() method. The event object that is passed to the runScript() function will tell you which range was edited.

function createEditTrigger() {
 ScriptApp.newTrigger("runScript")
   .forSpreadsheet(SpreadsheetApp.getActive())
   .onEdit()
   .create();
}

Create a Change trigger using Apps Script

You can configure the trigger to run whenever your spreadsheet's structure is modified by using the .onChange() method. The event object that is passed to the runScript() function will tell you how the spreadsheet was modified.

function createChangeTrigger() {
 ScriptApp.newTrigger("runScript")
   .forSpreadsheet(SpreadsheetApp.getActive())
   .onChange()
   .create();
}

Create a Form submit trigger using Apps Script

You can configure the trigger to run whenever a Google Form linked to your spreadsheet is submitted by using the .onFormSubmit() method. The event object that is passed to the runScript() function will contain the information that was submitted via the Google Form.

function createFormSubmitTrigger() {
 ScriptApp.newTrigger("runScript")
   .forSpreadsheet(SpreadsheetApp.getActive())
   .onFormSubmit()
   .create();
}

Check if a trigger already exists using Apps Script

You can get a list of triggers that were previously created by using ScriptApp.getProjectTriggers(). This will return an array of triggers and you can use this information to check if you're about to create a duplicate trigger.

The checkIfTriggerExists() function is an example of how to check if a trigger already exists.

function checkIfTriggerExists(eventType, handlerFunction) {
var triggers = ScriptApp.getProjectTriggers();
var triggerExists = false;
triggers.forEach(function (trigger) {
  if(trigger.getEventType() === eventType &&
    trigger.getHandlerFunction() === handlerFunction)
    triggerExists = true;
});
return triggerExists;
}

Conclusion

In this tutorial you learned how to create time based and event based triggers programmatically using Apps Script. When you write a lot of Apps Script code, it can be more efficient to programmatically create triggers instead of creating them using the Triggers UI in the Apps Script code editor.

Thanks for reading!


Have feedback for me?

I'd appreciate any feedback you can give me regarding this post.

Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!