Scheduling Tasks with Cron

Introduction to Scheduling Tasks with cron

Welcome to another exciting lesson on system automation! Today, we will delve into scheduling tasks automatically using cron. If you often find yourself needing to run specific tasks at regular intervals without manual intervention, then cron is the tool for you.

Cron is a time-based job scheduler in Unix-like operating systems. Users can set up and maintain automated jobs using cron syntax. While there are alternatives like at and systemd timers, cron is widely used for its simplicity and flexibility.

Let's get started!

Understanding Cron

Cron allows you to schedule tasks, known as "cron jobs," to be executed at specific times or intervals. The configuration of these jobs is stored in files called "crontabs" (cron tables). Each user on a system can have their own crontab, and there's also a system-wide crontab managed by the root user. Suppose you want to run a script that backs up your computer every night. Instead of manually running the script every night, you can use cron to run the script at any time.

Cron Syntax

Cron uses a simple and powerful syntax to define job schedules. The basic format for a cron job is:

* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └──── Day of the week (0 - 7) (both 0 and 7 mean Sunday)
│ │ │ └────── Month (1 - 12)
│ │ └──────── Day of the month (1 - 31)
│ └────────── Hour (0 - 23)
└──────────── Minute (0 - 59)

Each of these fields can be specified as:

  • A single number: 5 means "exactly at five".
  • A range of numbers: 1-5 means "1 to 5".
  • A list of numbers: 1,2,3 means "1 or 2 or 3".
  • An asterisk (*) wildcard means "every" possible value of this field.
  • /: Specifies step values. For example, */5 in the minutes field means "every 5 minutes".

Here are some examples:

Run a job every day at 5 AM

0 5 * * * /path/to/script.sh

Run a job every Monday at 3 PM

0 15 * * 1 /path/to/script.sh

Run a job every 15 minutes

*/15 * * * * /path/to/script.sh

Run a job every day at midnight

0 0 * * * /path/to/nightly_backup.sh

Run a job at 10 PM on the 1st of every month

0 22 1 * * /path/to/monthly_job.sh

Creating a Simple Cron Job

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal