Cron Expressions in Apps Script: Mastering Time Triggers

Cron Expressions in Apps Script: Mastering Time Triggers

Learn how to successfully automate your operations with Apps Script’s Cron Expressions. Utilize this beginner’s tutorial to master time triggers.

Are you trying to accurately and effectively automate operations in Google Apps Script? You’ve come to the proper location if so! The keys to mastering time triggers will be revealed as we delve into the realm of Cron Expressions in Apps Script in this beginner’s guide. You’ll be able to plan and automate your scripts like a pro once you have this information.

Cron expressions are a useful scheduling tool that let you precisely automate routine operations. These expressions specify precise time intervals for the tasks you’ve planned. For instance, your cron expression would be something like this if you wanted to run a script every weekday at 8:30 p.m.

30 20 * * 1-5

Time Triggers in Google Apps Script:

You may use Google Apps Script to effortlessly automate operations by taking advantage of time triggers. You might set up a timer to automatically email spreadsheets on workdays or download Gmail emails into your Google Drive, for example. You could run into restrictions while setting up repeating schedules, though. Imagine you want to run a script on Saturday and Sunday at around 3 PM. You would need to put up two distinct triggers to do this:

function 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();
}

With this strategy, managing more complicated triggers, such as a script that runs at 10 PM on the 15th of every other month, becomes more difficult. On the other hand, creating a cron expression for this task is simple:

**0 22 15 */2 ***

Similar to this, writing code to create a time trigger that runs at 10:30 am on the final day of the month would be far more complex than using a cron expression:

**30 10 L * ***

Google Script meets Cron Expressions:

By directly integrating cron expressions into Google Apps Script, there is an elegant solution to these problems. Let’s investigate how to use this workaround:

Load the Cron Parser Library:

The well-known “croner” package in Apps Script may be used to analyze cron expressions and determine forthcoming schedules.

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

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

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

  // Check if the fetched content contains the word "Cron"
  if (/Cron/.test(libraryContent)) {
    // Cache the library for 6 hours
    cache.put(key, libraryContent, 60 * 60 * 6);
    return libraryContent;
  }

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

Add Trigger with Cron Expression:

Now let’s build a function that loads the Cron library and, using the script’s timezone for date comparison, determines if a scheduled job is slated to run within the next five minutes.

const scheduledFunction = () => {
  // Run the trigger at 3:45 for the 1st 10 days of every 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('Hello, I am running via the time trigger!');
  }
};

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

A time trigger that runs scheduledFunction once every five minutes will be created using the addTrigger function. Every 5 minutes, it checks the cron schedule and, if the script is scheduled to execute, writes a message to the console. With additional flexibility and control, this method makes using Google Apps Script for complicated scheduling tasks easier.

Leave a Comment