In our previous articles (Parts 21 and 22), we explored simple triggers (such as onOpen and onEdit) that run automatically when a file is opened or an edit is made. Experiencing a script run completely on its own is one of the most rewarding parts of automation, isn’t it?
However, as you build real-world workflow automations, you will quickly encounter requirements like these:
- “I want data aggregated and a report generated automatically every morning at 9:00 AM!”
- “I want to send a one-time reminder at an exact date and time!”
- “When a user clicks a button, I want to schedule a recurring task that runs every Monday morning!”
- “Once a task is finished or expires, I want to automatically remove the scheduled timer!”
To handle all of these dynamically, Google Apps Script provides ScriptApp.newTrigger() and ScriptApp.deleteTrigger()!
Until now, you may have set timers manually by clicking the clock icon (Triggers menu) in the GAS editor. With these methods, you can create and delete triggers entirely via code with full control.
In this tutorial, inspired by daily operational tasks at our Sapporo Office, we will walk through the underlying mechanics, practical code examples, and the most common pitfalls beginners face, step by step!
1. What Does It Mean to “Manage Triggers via Code”?
Let’s first clarify the overall concept and contrast manual setup with programmatic configuration.
Manual Configuration vs. Dynamic Script Execution
There are two primary ways to run Google Apps Script on a schedule:
| Feature | Manual Setup (UI Clock Icon) | Programmatic Setup (ScriptApp.newTrigger) |
| Setup Method | Configured manually via mouse clicks in the editor | Created automatically by running script logic |
| Flexibility | Limited to predetermined, fixed times and intervals | Dynamic; can adapt to user-specified dates or conditions |
| Automation | Cannot be created or deleted inside running code | Creation and deletion can be 100% automated! |
| Primary Use Cases | Permanent daily or monthly recurring jobs | Dynamic reminders, one-time cleanup timers, system initialization |
Manual configuration is like manually setting an alarm clock on your nightstand every single night.
In contrast, ScriptApp.newTrigger() is like instructing an assistant bot: “Set an alarm for 7:00 AM tomorrow, and once it rings, clean up and put the alarm clock away!”
Why Do We Need to Delete Triggers with Code (deleteTrigger)?
You might wonder, “Creating triggers via code sounds great, but why do I also need code to delete them?”
The key reason is that Google Apps Script enforces a hard quota: a maximum of 20 installable triggers per user per project.
If your script repeatedly creates triggers without removing old ones, identical timers will pile up. This leads to serious issues, such as ten duplicate emails being sent every morning at 9:00 AM, or script crashes when reaching the quota limit.
That is why learning how to create triggers (newTrigger) and how to remove them (deleteTrigger) must always go hand in hand!
2. Breaking Down the Syntax: How to Write Trigger Code
The code chaining might look unfamiliar at first, but the underlying pattern is straightforward. Let’s inspect each component.
① Creating a Trigger: ScriptApp.newTrigger()
ScriptApp.newTrigger("targetFunctionName")
.timeBased()
.everyDays(1)
.atHour(9)
.create();
This uses what is known in software engineering as the “Builder pattern,” chaining methods together with dots (.).
ScriptApp.newTrigger("functionName")Declares that you are building a trigger for this specific function. Note that the function name must be passed as a string enclosed in double quotes" "..timeBased()Specifies that this is a time-driven (clock-based) trigger..everyDays(1)or.everyWeeks(1), etc.Defines the recurrence interval, such as daily or weekly..atHour(9)Designates the execution hour (around 9:00 AM). Note: GAS executes time-driven triggers within an approximate one-hour window (e.g., between 9:00 AM and 10:00 AM) to balance server load..create()The final method that commits and saves the trigger to your Google project.
② Deleting Existing Triggers: ScriptApp.deleteTrigger()
// 1. Retrieve all triggers associated with this project
var triggers = ScriptApp.getProjectTriggers();
// 2. Loop through and delete them one by one
for (var i = 0; i < triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.getProjectTriggers()Retrieves an array containing all currently active triggers in the project.ScriptApp.deleteTrigger(triggerObject)Removes the specified trigger. Remember to pass the trigger object itself, not the function name string!
3. STEP 1: Preparation – Create the Sapporo Office Morning Checklist
Let’s build working code together! For our example, we will set up a morning routine spreadsheet modeled after our operations at the Sapporo Office.
Steps
- Create a new Google Spreadsheet and name it “Sapporo Office Morning Checklist”.
- Rename the active sheet tab at the bottom to “Execution Log”.
- Enter headers in row 1 as follows:
| A | B | |
| 1 | Timestamp | Status |
Keep the “Execution Log” sheet open and active in your browser.
4. STEP 2: [Hands-On] Create a Daily 9 AM Trigger with ScriptApp.newTrigger()
First, we will write a script that registers a daily automated trigger directly into the project settings.
1. Enter the Code
Open the script editor from Extensions > Apps Script, remove any placeholder code, and paste the following snippet:
// [Main task to automate] (Invoked every morning around 9:00 AM)
function sendMorningReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Execution Log");
// Append the execution timestamp and message to the end of the sheet (using appendRow!)
sheet.appendRow([new Date(), "Morning routine report generated (Sapporo Office)"]);
}
// [Trigger registration function] (Run once to set up the daily timer)
function setDailyTrigger() {
// 1. Delete any existing duplicate triggers for this function first
deleteTriggerByName("sendMorningReport");
// 2. Schedule a daily trigger to execute sendMorningReport between 9 AM and 10 AM
ScriptApp.newTrigger("sendMorningReport")
.timeBased()
.everyDays(1)
.atHour(9)
.create();
Logger.log("Daily 9 AM trigger for 'sendMorningReport' successfully created!");
}
// [Safety helper] Deletes only triggers that match the specified handler function name
function deleteTriggerByName(functionName) {
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
if (triggers[i].getHandlerFunction() === functionName) {
ScriptApp.deleteTrigger(triggers[i]);
Logger.log("Removed outdated trigger for: " + functionName);
}
}
}
2. Key Architectural Details
deleteTriggerByName("sendMorningReport");This custom safety mechanism checks whether a trigger for that function already exists and deletes it before creating a new one. This ensures that clicking the setup button multiple times will never generate runaway duplicates.triggers[i].getHandlerFunction()Retrieves the target function name (as a string) associated with each trigger. We use this to accurately filter and target specific triggers.
3. Save and Run
- Click the Save (disk icon) at the top of the editor.
- Select
setDailyTriggerfrom the function dropdown and click “Run”. - On your first run, Google will display an “Authorization required” dialog. Follow the prompts to grant the necessary permissions.
When execution completes, check the Execution Log panel. If you see output like this, your setup was successful!
Info Removed outdated trigger for: sendMorningReport
Info Daily 9 AM trigger for 'sendMorningReport' successfully created!
4. Verify the Trigger in the Management Console
Let’s confirm that the trigger was actually registered in the Google Apps Script UI:
- Click the Triggers (alarm clock icon) on the left sidebar of the Apps Script editor.
- You should see an entry listed with the function “sendMorningReport”, event source set to “Time-driven”, and type set to “Day timer” (9am to 10am)!
Without clicking through manual configuration forms, running your script once configured the entire trigger schedule automatically!
5. STEP 3: [Hands-On] Delete Triggers Automatically with ScriptApp.deleteTrigger()
Now let’s practice cleaning up and removing triggers programmatically.
This cleanup function comes in handy when you want to pause all scheduled background tasks or completely reset your project environment.
1. Add the Cleanup Function
Append the following code to the bottom of your script and save:
// [Complete cleanup function] Deletes every trigger registered in this project
function clearAllTriggers() {
// 1. Fetch all triggers currently in the project
var allTriggers = ScriptApp.getProjectTriggers();
// 2. Loop and delete each trigger
for (var i = 0; i < allTriggers.length; i++) {
ScriptApp.deleteTrigger(allTriggers[i]);
}
Logger.log("Successfully deleted all " + allTriggers.length + " trigger(s)!");
}
2. Execute and Confirm
- Select
clearAllTriggersin the function list and click “Run”. - Switch back to the Triggers menu on the left sidebar.
If the table is completely empty, your cleanup routine worked perfectly!
6. Advanced Pattern: “Self-Deleting Disposable One-Time Timers”
The real architectural superpower of newTrigger and deleteTrigger appears when creating one-time timers that execute once at a specific future moment and immediately delete their own trigger upon completion.
For example, you could schedule a reminder to be sent to a teammate at the Sapporo Office 10 minutes from now, with the timer automatically disposing of itself as soon as the email is delivered.
// Schedules a one-time task to run 10 minutes from now
function setOneTimeTimer() {
// Calculate timestamp 10 minutes in the future
var triggerTime = new Date();
triggerTime.setMinutes(triggerTime.getMinutes() + 10);
// Create a time-based trigger set for that specific moment
ScriptApp.newTrigger("oneTimeTask")
.timeBased()
.at(triggerTime)
.create();
Logger.log("One-time timer scheduled for 10 minutes from now!");
}
// Target function that executes 10 minutes later
function oneTimeTask() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Execution Log");
// Run main processing
sheet.appendRow([new Date(), "One-time task executed successfully!"]);
// [Cleanup] Self-delete the trigger to prevent clutter!
deleteTriggerByName("oneTimeTask");
}
By adopting this “execute and self-delete” pattern, you can queue dynamic tasks reliably without running into project trigger quotas!
7. The 5 Common Traps for Beginners and How to Fix Them
Here are the most frequent pitfalls developers encounter when working with programmatic triggers, along with straightforward solutions.
Trap 1: Duplicate Triggers Multiply Every Time Code Runs
Symptom
After testing setDailyTrigger() five times, your morning task runs five consecutive times every morning.
Root Cause
newTrigger() creates a brand-new trigger object on every invocation. It does not overwrite or update existing triggers.
Fix
Make it a rule to invoke a helper like deleteTriggerByName("functionName") before calling newTrigger().
Trap 2: Adding Parentheses like newTrigger("myFunction()")
Symptom
The execution fails with Exception: Invalid argument: functionName.
Root Cause
The argument passed to newTrigger() must only be the function identifier as a string. Including parentheses () causes a syntax error.
- ✕
ScriptApp.newTrigger("sendMorningReport()") - ◯
ScriptApp.newTrigger("sendMorningReport")
Trap 3: Passing a String to deleteTrigger()
Symptom
The execution throws Exception: Cannot find method deleteTrigger(string).
Root Cause
deleteTrigger() expects an actual Trigger object (such as one returned by ScriptApp.getProjectTriggers()), not a string with the function name.
- ✕
ScriptApp.deleteTrigger("sendMorningReport") - ◯
ScriptApp.deleteTrigger(triggerObject)
Trap 4: atHour(9) Doesn’t Run Exactly at 9:00 AM Sharp
Symptom
A trigger scheduled for 9:00 AM fires at 9:24 AM or 9:45 AM.
Root Cause
This is expected Google Apps Script platform behavior, not a bug.
To distribute Google Cloud infrastructure load across millions of accounts, hourly triggers execute randomly within the specified 60-minute window (e.g., between 9:00 AM and 10:00 AM). Design your business workflows expecting this margin of tolerance rather than requiring exact second precision.
Trap 5: Reaching the 20-Trigger Limit
Symptom
Trigger creation fails with Exception: This script has too many triggers. Area limit: 20.
Root Cause
Google Apps Script caps the number of triggers at 20 per user per project.
If expired or orphaned triggers are not cleaned up with deleteTrigger(), you will quickly hit this quota ceiling. Always build cleanup routines for one-time operations!
8. Summary & What’s Next
In this guide, we explored how to programmatically register and remove triggers using ScriptApp.newTrigger() and ScriptApp.deleteTrigger().
Key Takeaways
- Use
ScriptApp.newTrigger("functionName")to generate dynamic, schedule-based triggers directly from code. - Always clean up existing duplicate triggers with
deleteTrigger()before creating new ones. - For one-time tasks, use the self-deleting pattern where the function cleans up its own trigger after finishing.
- Remember that Google Apps Script time-based triggers execute within an approximate 1-hour window.
You now possess the capability to manage background schedules dynamically without ever touching manual editor settings!
Now that your automated background jobs are humming smoothly, Part 24 will dive into user interface interaction with SpreadsheetApp.getUi()!
We will learn how to prompt users with “Are you sure you want to proceed?” alert dialogs and Yes/No confirmation popups, taking your spreadsheets into full-fledged custom business application territory. Stay tuned!
