If you’ve ever wanted your Linux server to run tasks automatically, like cleaning logs, backing up databases, or sending reports, then cron jobs are your best friend. Cron is a time-based job scheduler built into Unix-like operating systems, and it’s one of the most powerful automation tools for system admins and developers.
In this article, we’ll walk through what cron jobs are, how the syntax works, real-world examples, and how we can set them up in our system.
What is a Cron Job?
A cron job is a command or script that is scheduled to run at a specific time or interval. The cron service (crond
) runs in the background and checks a special configuration file. This configuration file is called a crontab (short for "cron table") to know what to execute.
Each user on a system can have their own crontab file, and there’s also a system-wide crontab located at /etc/crontab
.
Cron Syntax Explained
Cron syntax might be confusing. But it’s actually quite simple. Every cron job is defined with five time fields followed by the command to run. Here’s a breakdown:
* * * * * command_to_execute
- - - - -
| | | | |
| | | | +---- Day of week (0 - 6) (Sunday=0 or 7)
| | | +--------- Month (1 - 12)
| | +-------------- Day of month (1 - 31)
| +------------------- Hour (0 - 23)
+------------------------ Minute (0 - 59)
Special Characters
-
*
→ every value -
,
→ list of values (e.g.1,15
) -
-
→ range (e.g.1-5
) -
/
→ step (e.g.*/5
means every 5 units)
Cron Job Examples
Let’s go through some practical examples:
*/5 * * * * echo "Hello" >> /tmp/hello.log
Run every 5 minutes.0 0 * * * /usr/bin/backup.sh
Run a backup script every day at midnight.30 14 * * 1
Run at 2:30 PM every Monday.0 */6 * * * /usr/bin/update.sh
Run every 6 hours.15 9-17 * * 1-5 /usr/bin/send_report.sh
Run at 9:15, 10:15, …, 5:15 during working hours, Monday through Friday.
Setting Up a Cron Job
- Install cron (if not already installed) On CentOS/RHEL:
sudo yum install -y cronie
sudo systemctl enable crond
sudo systemctl start crond
On Ubuntu/Debian:
sudo apt-get update
sudo apt-get install -y cron
sudo systemctl enable cron
sudo systemctl start cron
- Edit the crontab To add a job for the user:
crontab -e
- Verify cron jobs
crontab -l
- Check if it’s working For example, add:
*/2 * * * * echo "Cron is working!" >> /tmp/test_cron.log
Then wait a few minutes and run:
cat /tmp/test_cron.log
Common Use Cases
- Automating backups
- Rotating or cleaning log files
- Sending periodic emails or reports
- Updating packages or databases
- Monitoring disk usage
Final Thoughts
Cron jobs are simple yet powerful. With a few lines in crontab, we can automate tasks to run on time, every time. Whether managing servers or automating workflows, knowing cron is essential.
Top comments (0)