1. Cron Jobs

Cron Jobs: the guide

Max Rozen

Max Rozen | Last updated: March 13, 2024

If you don't know what a "cron job" is or how the cron job expression syntax works (and at this point are too afraid to ask), you're in the right place.

In this guide, we'll dive into what is a cron job, how they work, and the details that often get overlooked, like cron job schedule syntax and common cron job errors.

What is a cron job?

To understand what cron jobs are, we should probably talk about what cron is first.

cron is a time-based job scheduler in Unix-like operating systems. Users can schedule jobs (commands or scripts) to run at specific times or on specific days.

For example, you can schedule a job that backs up your database every night at midnight, or send out an email report to customers every Friday afternoon.

How cron jobs work

You write a small script that performs a specific action. This script is then executed by a cron daemon at specified intervals. The cron daemon is a background process that runs on the server and runs tasks at scheduled intervals. It scans for tasks to run every minute, runs them, and manages the output (it can send job output as an email to the user or save it to a specified log file).

The schedule for these jobs is stored in a special file known as the crontab (cron table). Each user can have their own crontab, and commands in the crontab are executed as the user who owns the crontab. The syntax of the crontab file specifies the minute, hour, day, month, and day of the week that a task should be executed.

Cron job schedule syntax

In a crontab file, each line represents a single cron job and follows a particular syntax. A cron expression typically consists of five fields, separated by spaces, followed by the command to be executed.

* * * * * [optionally, username to run as] command-to-be-executed
- - - - -
| | | | |
| | | | +---- Day of the week (0 - 7) [Both 0 and 7 represent Sunday]
| | | +------ Month (1 - 12)
| | +-------- Day of the month (1 - 31)
| +---------- Hour (0 - 23)
+------------ Minute (0 - 59)

Some tools such as node-cron use a sixth field to represent seconds.

Special characters

  • Asterisk (*): The asterisk signifies "any" or "every." For example, an asterisk in the minute field would mean "every minute."
  • Comma (,): You can use a comma to specify multiple values. For instance, 1,15 in the minute field would mean "at 1 and 15 minutes past the hour."
  • Hyphen (-): A hyphen defines a range. For example, 1-5 in the hour field would indicate "every hour between 1am and 5am."
  • Slash (/): A slash specifies increments. For example, */15 in the minute field would indicate "every 15 minutes."

© 2024 OnlineOrNot SASU, 66 Av. des Champs-Élysées 75008 Paris
Made with in Sydney, Australia 🇦🇺 and Toulouse, France 🇫🇷