...
Skip to main content
Print

Crontab: How to Set Up a Cron Job on Linux

You set up a cron job on Linux with the crontab -e command. In it, you specify per line when a command or script should run automatically, for example a backup every night or a check every five minutes. In this article you read how the syntax works, how to add a cron job and how to check that it runs.

What is a cron job?

Cron is the Linux scheduler. A cron job is a task that cron runs at fixed times, without you having to be there. On a VPS you use cron jobs for backups, cleaning up log files, sending reports or starting scripts, for example.

The cron job syntax

Each line consists of five time fields, followed by the command to run:

# minuut uur dag maand weekdag commando
  30     2   *   *     *     /root/backup.sh
  • Minute: 0 to 59
  • Hour: 0 to 23
  • Day of the month: 1 to 31
  • Month: 1 to 12
  • Day of the week: 0 to 7, where 0 and 7 are both Sunday

An asterisk means every value. The example above therefore runs the script every night at 02:30.

Common examples

*/5 * * * * /root/controle.sh
0 * * * * /root/elk-uur.sh
0 3 * * 1 /root/weekrapport.sh
0 0 1 * * /root/maandelijks.sh
@reboot /root/start.sh

From top to bottom: every five minutes, every full hour, every Monday at 03:00, the first day of every month at midnight, and once when the server starts.

Adding a cron job step by step

Step 1: open your crontab

crontab -e

The first time you choose an editor. Nano is the easiest for most users.

Step 2: add your task

Add a new line at the bottom with the time and the command. Always use full paths, because cron does not have the same environment as your terminal. Save the file and close the editor.

Step 3: check your cron jobs

crontab -l

This shows all cron jobs of the current user.

Logging output and errors

Send the output of your cron job to a log file, so you can see whether it runs correctly:

30 2 * * * /root/backup.sh >> /var/log/backup.log 2>&1

If a cron job does not run, check the system log:

grep CRON /var/log/syslog

On AlmaLinux the cron log is in /var/log/cron.

Common mistakes

  • Relative paths: always use full paths to scripts and program files, for example /usr/bin/php instead of php.
  • Script not executable: make your script executable with chmod +x /root/backup.sh.
  • Time zone: cron uses the time zone of the server. Check it with timedatectl.

Related articles

Table of Contents