Using Cron jobs

2 minute read

Published:

Simply put, cron jobs are jobs/tasks (pieces of executable code, on Linux or Mac) that are run on a predefined schedule. For example,

  • Every Wednesday, at noon
  • Mondays in January, March, and May at 1 am
  • Thursdays and Sundays in December at 4 pm

These times will need to expressed as a cron expression, which we’ll get to in a minute!

In the context of GitHub, they can be used in a GitHub action to run any code on whatever schedule you’d like.

Lets say that you know a database gets updated weekly on Tuesday evening. Rather than having to manually visit the website on Wednesday morning, pull the data and process it, you decide you want to set up a GitHub action to do this for you. Enter the cron job!

In this case, in your GitHub action you’d add the following lines (toward the top of your action)

   schedule:
   # uses UTC/GMT time (+ 5 hrs)
    - cron: "0 17 * * 3" # Every Wednesday at 1200 hrs = 1700 UTC

Of course, you’ll need to adhere to the GitHub action syntax guidelines to know exactly where to place this, but it is that simple. You’d also need to configure the rest of the action to access the data base, pull your data, process it, then either commit to your repo or send yourself an email!

Note: Times are Coordinated Universal Time (UTC)

Cron expressions

From docs.github.com, “Cron syntax has five fields separated by a space, and each field represents a unit of time.”

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of the month (1 - 31)
│ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
│ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
│ │ │ │ │
* * * * *

And there are several special characters that can be used to specify a particular schedule.

Some examples:

  • 0 0 * * 0 - Every Sunday at midnight
  • 0 * * * 1 - Every hour on Mondays
  • 0 6,18 * * * - 6 am and 6 pm every day
  • */15 * * * - Every 15 minutes
  • 0 1 * 1,3,5 1 - Monday at 1am in January, March, and May
  • 0 4 * 12 0,4 - Sundays and Thursdays in December at 4am
  • 0 0 1-15 * * - Day 1 through 15 of every month at midnight

To help with the cron syntax there are several websites. Crontab.guru is worth using! Have fun!