
How to Schedule Tasks with Cron: A Beginner’s Guide
Automating repetitive tasks is essential for efficiency, whether you’re managing a server, running scripts, or performing routine maintenance. Cron, a time-based job scheduler in Unix-like systems, allows you to schedule tasks effortlessly.
What is Cron?
Cron is a daemon that runs scheduled commands (cron jobs) at specified times. These jobs are defined in crontab (cron tables), which are configuration files that specify shell commands to run periodically.
Basic Cron Syntax
A cron job follows this structure:
* * * * * command-to-execute │ │ │ │ │ │ │ │ │ └── Day of the week (0-6, Sun=0) │ │ │ └──── Month (1-12) │ │ └────── Day of the month (1-31) │ └──────── Hour (0-23) └────────── Minute (0-59)
Examples:
-
Run a script every day at 3 AM:
0 3 * * * /path/to/script.sh
-
Run a backup every Sunday at midnight:
0 0 * * 0 /path/to/backup.sh
-
Run a task every 10 minutes:
*/10 * * * * /path/to/task.sh
How to Edit Crontab
-
Open crontab for editing:
crontab -e
-
Add your cron job following the syntax.
-
Save and exit (in
vim
, press:wq
; innano
,Ctrl+X
, thenY
).
Viewing and Managing Cron Jobs
-
List active cron jobs:
crontab -l
-
Remove all cron jobs:
crontab -r
Conclusion
Cron is a powerful tool for automating tasks on Unix-like systems. With simple syntax and flexible scheduling, it helps streamline workflows without manual intervention.
How to Schedule Tasks with Cron (F.A.Q)
How do I run a cron job every hour?
0 * * * * /path/to/command
Can I log cron job output?
Yes, redirect output to a file:
* * * * * /path/to/command >> /path/to/logfile.log 2>&1
Why isn’t my cron job running?
-
Check if the cron service is running (
systemctl status cron
). -
Ensure the command has executable permissions (
chmod +x
). -
Verify paths are absolute (not relative).
How do I run a cron job as a specific user?
Edit that user’s crontab:
sudo crontab -u username -e