How to use cron on Linux

The cron system is a method to automatically run commands on a schedule.
30 readers like this.
Cron expression

CC BY-SA Seth Kenlon

The cron system is a method to automatically run commands on a schedule. A scheduled job is called a cronjob, and it’s created in a file called a crontab. It’s the easiest and oldest way for a computer user to automate their computer.

Writing a cronjob

To create a cronjob, you edit your crontab using the -e option:

$ crontab -e 

This opens your crontab your default text editor. To set the text editor explicitly, use the EDITOR environment variable:

$ EDITOR=nano crontab -e 

Cron syntax

To schedule a cronjob, you provide a cron expression followed by the command you want your computer to execute. The cron expression schedules when the command gets run:

  • minute (0 to 59)

  • hour (0 to 23, with 0 being midnight)

  • day of month (1 to 31)

  • month (1 to 12)

  • day of week (0 to 6, with Sunday being 0)

An asterisk (*) in a field translates to "every." For example, this expression runs a backup script at the 0th minute of every hour on every day of every month:

0 * * * * /opt/backup.sh

This expression runs a backup script at 3:30 AM on Sunday:

30 3 * * 0 /opt/backup.sh

Simplified syntax

Modern cron implementations accept simplified macros instead of a cron expression:

  • @hourly runs at the 0th minute of every hour of every day

  • @daily runs at the 0th minute of the 0th hour of every day

  • @weekly runs at the 0th minute of the 0th hour on Sunday

  • @monthly runs at the 0th minute of the 0th hour on the first day of the month

For example, this crontab line runs a backup script every day at midnight:

/opt/backup.sh @daily

How to stop a cronjob

Once you've started a cronjob, it's designed to run on schedule forever. To stop a cronjob once you've started it, you must edit your crontab, remove the line that triggers the job, and then save the file.

$ EDITOR=nano crontab -e 

To stop a job that's actively running, use standard Linux process commands to stop a running process.

It’s automated

Once you’ve written your crontab, save the file and exit your editor. Your cronjob has been scheduled, so cron does the rest.

What to read next

How I use cron in Linux

No time for commands? Scheduling tasks with cron means programs can run but you don't have to stay up late.

Seth Kenlon
Seth Kenlon is a UNIX geek, free culture advocate, independent multimedia artist, and D&D nerd. He has worked in the film and computing industry, often at the same time.

4 Comments

How do you turn off a cron job once you've started it?

The examples are backwards! - the command goes at the end after the time spec, not at the front.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.