Search code examples
google-apps-scripttriggersgoogle-sheets-api

How to create a yearly time-driven trigger?


I'm attempting to create a time-based trigger to execute my incrementCell function once a year on a specified date at 1 AM in perpetuity. When attempting to run below

ScriptApp.newTrigger("incrementCell").timeBased().atDate(2018, 1, 4).atHour(1).everyWeeks(52).create();

I received an "Already chosen a specific date time with at() or atDate()." error.

Interestingly, the line immediately below does not error out:

ScriptApp.newTrigger("incrementCell").timeBased().atDate(2018, 1, 4).create();

Solution

  • Google Apps Script doesn't support yearly triggers but you can use a workaround. Create a monthly trigger that runs on the 1st of every month, and if the month is January, run the actual function.

    function createYearlyTrigger() {
      ScriptApp.newTrigger("shouldTriggerRun")
      .timeBased().onMonthDay(1).atHour(1).create();
    }
    
    function shouldTriggerRun() {
      var date = new Date();
      if (date.getMonth() === 0) {
        incrementCell();
      }  
    }