The best way to Use Cron Expressions to Create Time Triggers in Apps Script

Shubham
6 Min Read

Cron is a scheduling software that helps you run duties at recurring intervals. You employ a cron expression to specify the precise timing in your scheduled process. For instance, if you need a schedule to run each week day at 8

pm, the cron expression would seem like this:

30 20 * * 1-5

Cron Expressions

Listed here are some extra sensible examples that can assist you perceive the cron expression.

Cron Expression Description
0 0 * * * day by day at midnight
0 */2 * * * each 2 hours
0 10 * * FRI,SAT each Friday and Saturday at 10 am
30 9 */15 * * at 9 am on each fifteenth day
0 0 1 */3 * first day of each quarter

Time Triggers in Google Apps Script

Google Apps Script helps time-driven triggers that can assist you run duties within the background mechanically. As an illustration, you possibly can setup a time set off in Apps Script to email spreadsheets each weekday. Or a set off to download emails from Gmail to your Google Drive.

Time-based triggers in Apps Script have sure limitations, notably in relation to establishing recurring schedules. For instance, if you wish to create a easy cron job that runs each weekend at round 3 PM, you’d have to arrange two separate triggers like this:

perform createTimeTrigger() {
  ScriptApp.newTrigger('functionName')
    .timeBased()
    .everyWeeks(1)
    .onWeekDay(ScriptApp.Weekday.SUNDAY)
    .atHour(15)
    .create();

  ScriptApp.newTrigger('functionName')
    .timeBased()
    .everyWeeks(1)
    .onWeekDay(ScriptApp.Weekday.SATURDAY)
    .atHour(15)
    .create();
}

Managing extra advanced triggers, like one which runs at 10 PM on the fifteenth of each alternate month, turns into much more difficult. In distinction, writing a cron expression for that is fairly simple: 0 22 15 */2 *. Equally, making a time set off that runs at 10

am on the final day of each month would contain way more code that writing a cron expression: 30 10 L * *

Google Script meets Cron Expressions

The cron syntax is highly effective and helps difficult recurring schedules however, sadly, it isn’t out there inside Google Apps Script. However we now have a straightforward workaround.

We will write our time set off schedules in cron expressions straight inside Apps Script.

Load the Cron Parser Library

We are going to use the favored croner library in Apps Script to parse cron expressions and calculate the upcoming schedules.

const loadCronLibrary = () => {
  const key = 'croner@7';
  const url = 'https://cdn.jsdelivr.internet/npm/croner@7/dist/croner.umd.min.js';
  const cache = CacheService.getScriptCache();

  // Examine if the library content material is already cached
  const cachedContent = cache.get(key);
  if (cachedContent) return cachedContent;

  // Fetch the library content material from the desired URL
  const libraryContent = UrlFetchApp.fetch(url, {
    muteHttpExceptions: false,
  }).getContentText();

  // Examine if the fetched content material comprises the phrase "Cron"
  if (/Cron/.check(libraryContent)) {
    // Cache the libary for six hours
    cache.put(key, libraryContent, 60 * 60 * 6);
    return libraryContent;
  }

  throw new Error('The cron library is unavailable');
};

Add Set off with Cron Expression

Subsequent, we’ll create a perform that hundreds the Cron library and checks if a scheduled process is ready to execute throughout the subsequent 5 minutes. It makes use of the script’s timezone to check the dates.

const scheduledFunction = () => {
  // Run the set off at 3:45 for the first 10 days of each month
  const cronExpression = '45 3 1-10 * *';
  eval(loadCronLibrary());
  const job = Cron(cronExpression);
  const timeDifference = (job.nextRun() - new Date()) / (1000 * 60);
  if (Math.abs(timeDifference) <= 5) {
    Logger.log('Howdy, I'm working by way of the time set off!');
  }
};

const addTrigger = () => {
  ScriptApp.newTrigger('scheduledFunction').timeBased().everyMinutes(5).create();
};

The addTrigger perform would create the time set off that will invoke the scheduledFunction each 5 minutes. The cron schedule is checked each 5 minutes, and whether it is scheduled to run, the Howdy message can be logged to the console.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *