How to Schedule Cron Jobs in Ubuntu
Automating repetitive tasks in Ubuntu is efficiently handled by Cron, a built-in time-based job scheduler in Linux operating systems. This guide provides a quick overview of how to open the crontab configuration, understand the distinct five-field time syntax, and successfully schedule scripts or commands to run automatically at specific intervals. By the end of this article, you will be able to set up, modify, and manage your own recurring background tasks seamlessly.
Understanding the Crontab Syntax
Before adding tasks, it is essential to understand how Cron interprets time. Every cron job line consists of a time schedule followed by the absolute path to the command or script you want to execute.
The time configuration uses five asterisks, which represent different time fields:
.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12)
| | | | .---- day of week (0 - 6) (Sunday to Saturday)
| | | | |
* * * * * /path/to/command
You can use specific values, ranges (like 1-5), lists
(like 1,3,5), or intervals (like */15 for
every 15 minutes) in place of the asterisks to define your schedule.
Opening the Cron Configuration File
To add or edit your recurring tasks, you need to open your user-specific crontab file. Run the following command in your terminal:
crontab -eIf this is your first time running the command, Ubuntu will prompt
you to select a text editor. Choosing nano (usually option
1) is highly recommended for beginners because of its straightforward
interface.
Examples of Common Cron Schedules
Once the crontab file is open in your editor, scroll to the bottom of the file and add your scheduled tasks on new lines.
Running a Script Every Hour
To run a backup script at the start of every hour, use this configuration:
0 * * * * /usr/bin/python3 /home/user/backup.py
Running a Command Daily at Midnight
To clear a cache folder every night at exactly 12:00 AM:
0 0 * * * /usr/bin/rm -rf /home/user/cache/*
Running a Task Every Monday Morning
To trigger a status report script every Monday morning at 8:30 AM:
30 8 * * 1 /home/user/scripts/weekly_report.sh
Saving and Verifying Your Tasks
After typing your cron job into the editor, you need to save and
exit. In nano, press CTRL + O to write the
changes, press Enter to confirm the filename, and then
press CTRL + X to exit the editor. The terminal will
display a message stating crontab: installing new crontab,
which confirms your changes are live.
To verify that your tasks were successfully saved without opening the editor again, list your active cron jobs by running:
crontab -l