Scheduling Tasks with Cron

Run scripts and commands automatically at set times with cron and its five-field schedule.

~7 min Beginner

What is cron?

Cron is a service that runs commands on a schedule. You tell it "run this script every night at 2 AM", and it does, whether or not you are logged in. It is used for backups, cleanup, reports and health checks.

The service that runs the jobs is called the cron daemon (crond). The list of scheduled jobs is called a crontab ("cron table"). Each user has their own crontab.

Editing your crontab

crontab -e
crontab -l
crontab -r
  • crontab -e opens your crontab in an editor so you can add or change jobs. The first time, you may be asked to choose an editor such as nano.
  • crontab -l lists your jobs.
  • crontab -r removes all your jobs, so be careful.

Each line in the file is one job.

The five time fields

A job line has five time fields and then the command:

┌───────── minute (0-59)
│ ┌─────── hour (0-23)
│ │ ┌───── day of month (1-31)
│ │ │ ┌─── month (1-12)
│ │ │ │ ┌─ day of week (0-7, Sunday is 0 or 7)
│ │ │ │ │
* * * * *  command to run

The order is always: minute, hour, day of month, month, day of week. The command runs when all fields match the current time. So 0 2 * * * means minute 0, hour 2, every day of the month, every month, every day of the week, which is every day at 2:00 AM.

Special characters

  • * means "every value".
  • , makes a list: 1,15 is the 1st and the 15th.
  • - makes a range: 1-5 is Monday to Friday in the day-of-week field.
  • / makes a step: */10 is every 10 units.

Reading schedules

*/15 * * * *   check.sh
30 8 * * 1-5   report.sh
0 0 1 * *      monthly.sh
@reboot        start.sh
  • */15 * * * *: every 15 minutes.
  • 30 8 * * 1-5: at 8:30 AM, Monday to Friday.
  • 0 0 1 * *: at midnight on the 1st of every month.
  • @reboot: once, every time the system boots.

To run something every 10 minutes, use */10 * * * *.

Why cron jobs fail silently

A job that works in your terminal can fail in cron. Cron runs with a very small environment: a short PATH, no aliases and a different working directory. It also has no screen, so error messages go nowhere.

Two rules fix most problems:

  1. Use full paths for the script and for any files it uses.
  2. Log the output, including errors, so you can see what happened.
0 2 * * * /home/alex/backup.sh >> /home/alex/backup.log 2>&1

>> appends the output to a log file and 2>&1 sends error messages to the same place.

Testing a job

Set the schedule to * * * * *, which runs every minute, and watch the log for a few minutes. When it works, change it to the real schedule. Also make sure the script is executable with chmod +x.

Sign up to track your progress Mark lessons as read and pick up where you left off Sign up free to unlock this practice Your first practice lesson is free to try. Create an account to unlock the rest and save your progress