Programmatically delete existing time-based triggers and create a new one, in Google Apps Script

In Software Engineering, Snippet
function createTimeTrigger(minutesToUpdate) {
  /*** 
   * Removes existing time triggers. Then create a new minutes-based one.
   *
   * Arguments:
   * minutesToUpdate -- integer that must be one of 1, 5, 10, 15, or 30
   *
   * References:
   * https://developers.google.com/apps-script/managing_triggers_programmatically
   * http://googleappsdeveloper.blogspot.com/2012/04/introducing-script-service.html
   ***/

  // Default arguments
  var minutesToUpdate = typeof minutesToUpdate !== 'undefined' ? minutesToUpdate : 15;

  // Remove existing clock triggers
  var allTriggers = ScriptApp.getScriptTriggers();  
  for (i in allTriggers) {
    Logger.log("Trigger ID: " + allTriggers[i].getUniqueId()
               + "\nTrigger handler function: "
               + allTriggers[i].getHandlerFunction()
               + "\nTrigger type: " + allTriggers[i].getEventType()
               + "\n-------------------------");
    if (allTriggers[i].getEventType() == "CLOCK") {
      ScriptApp.deleteTrigger(allTriggers[i]);
    }
  }

  // Create a new clock trigger
  var minutesTimer = ScriptApp.newTrigger("updateRSS")
      .timeBased()
      .everyMinutes(minutesToUpdate)
      .create();
}

Leave a Reply