How to Schedule a Command with Cron in Ubuntu Terminal

One of the greatest strengths of a Linux server is its ability to automate repetitive tasks. If you need to run a backup script every night at 3:00 AM, clear out a temporary log directory every Sunday, or restart a specific service every hour, you do not need to log into the terminal and type the commands manually. You can hand the schedule over to cron.

Cron is a time-based job scheduler built deep into the heart of Ubuntu. It constantly watches the system clock in the background, waking up every single minute to check if there are any commands it needs to execute.

Understanding the Crontab

You interact with the cron daemon by editing a specific text file called a “crontab” (cron table). Every user on the server (including the root administrator) gets their own personal crontab.

  1. Open your terminal or SSH into your Ubuntu server.
  2. To edit your personal schedule, type the following command and press Enter:
crontab -e

(If this is your first time running the command, Ubuntu might ask you to choose a text editor. Press 1 for Nano, as it is the easiest to use).

You are now looking at the crontab file. At the very bottom of the file (below all the commented instructional text), you can add your new scheduled tasks.

The Cron Syntax (The 5 Stars)

Writing a cron job requires a very specific syntax. Every command must be preceded by five parameters (often represented as five asterisks: * * * * *). These parameters represent time, reading from left to right:

  1. Minute (0 – 59)
  2. Hour (0 – 23, in military time)
  3. Day of the Month (1 – 31)
  4. Month (1 – 12)
  5. Day of the Week (0 – 7, where both 0 and 7 represent Sunday)

An asterisk (*) means “every.” So, * * * * * means “run this command every minute of every hour of every day.”

Practical Examples

To run a backup script (located at /home/user/backup.sh) every day at exactly 2:30 AM, you would write:

30 2 * * * /home/user/backup.sh

To run a script every Sunday at 5:00 PM (17:00 military time), you would write:

0 17 * * 0 /home/user/sunday_clean.sh

To run a command every 15 minutes, you use a forward slash (/) to indicate an interval:

*/15 * * * * /home/user/check_status.sh

Saving and Verifying

Once you have typed your cron job at the bottom of the file:

  1. Press Ctrl + O to save the file, and press Enter to confirm.
  2. Press Ctrl + X to exit the Nano editor.

The terminal will output a message saying crontab: installing new crontab. Your schedule is now active. To double-check that your jobs were saved correctly, you can list the contents of your crontab without opening the editor by typing:

crontab -l

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.