Cron jobs are the backbone of Linux automation, letting you schedule scripts, backups, maintenance tasks, and monitoring without manual intervention. Whether you're managing a single VPS or a fleet of servers, understanding cron is essential for any sysadmin or developer working with Linux hosting environments.
This guide walks you through setting up your first cron job from zero to a working result, with commands, syntax explanations, and troubleshooting steps you can follow immediately.
What Is a Cron Job?
A cron job is a scheduled task that runs automatically at specified intervals on Linux and Unix-like systems. The cron daemon runs in the background and executes commands from a configuration file called a crontab (cron table). Each user can have their own crontab, and the system has a separate crontab for system-wide tasks.
Common use cases include:
- Automated backups of databases and files
- Log rotation and cleanup
- SSL certificate renewal checks
- WordPress plugin and core updates
- Server health monitoring and alerts
- Email queue processing
- Clearing cache directories
Prerequisites
Before you begin:
- SSH access to your Linux server with appropriate user permissions
- Basic command-line familiarity
- The
cronservice installed and running (pre-installed on most distributions)
Verify cron is running:
sudo systemctl status cron
On some distributions, the service is called crond:
sudo systemctl status crond
If it's not running, start it:
sudo systemctl start cron
sudo systemctl enable cron
Step 1: Understand Crontab Syntax
Before creating your first cron job, you need to understand the crontab syntax. Each cron job is defined on a single line with six fields:
* * * * * command-to-execute
│ │ │ │ │
│ │ │ │ └─── Day of week (0-7, where 0 and 7 = Sunday)
│ │ │ └───── Month (1-12)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)
Special characters:
*– Any value (every minute, hour, day, etc.),– List separator (1,15,30 means 1st, 15th, and 30th)-– Range (1-5 means 1 through 5)/– Step values (*/15 means every 15 units)
Common schedule examples:
# Every minute
* * * * *
# Every hour at minute 0
0 * * * *
# Every day at 2:30 AM
30 2 * * *
# Every Monday at 9:00 AM
0 9 * * 1
# Every 15 minutes
*/15 * * * *
# First day of every month at midnight
0 0 1 * *
# Weekdays at 6:00 PM
0 18 * * 1-5
Step 2: Choose Where to Create Your Cron Job
You have three main options:
User Crontab
Runs as your user account. Best for user-specific tasks, web application maintenance, and when you don't need root privileges.
crontab -e
Root Crontab
Runs as root. Use for system-level tasks, package updates, or operations requiring elevated permissions.
sudo crontab -e
System Crontab Files
Located in /etc/crontab and /etc/cron.d/. Allows specifying which user should run the job. Best for distribution packages and system services.
For most hosting scenarios, user crontabs are sufficient and safer.
Step 3: Create Your First Cron Job
Let's create a simple cron job that logs the current date every minute for testing purposes.
Open your crontab:
crontab -e
If this is your first time, you'll be prompted to choose an editor. Select your preference (nano is easiest for beginners).
Add this line at the bottom:
* * * * * echo "Cron ran at $(date)" >> /home/yourusername/cron-test.log
Replace yourusername with your actual username, or use the $HOME variable:
* * * * * echo "Cron ran at $(date)" >> $HOME/cron-test.log
Save and exit:
- In nano:
Ctrl+Oto save,Enterto confirm,Ctrl+Xto exit - In vim: Press
Esc, type:wq, pressEnter
You'll see a message confirming the crontab was installed:
crontab: installing new crontab
Step 4: Verify the Cron Job Is Running
Wait at least one minute, then check the log file:
cat ~/cron-test.log
You should see entries appearing each minute:
Cron ran at Wed Jul 01 06:55:01 UTC 2026
Cron ran at Wed Jul 01 06:56:01 UTC 2026
If you see these entries, congratulations—your cron job is working.
View your active crontab:
crontab -l
This lists all cron jobs for your user.
Step 5: Create a Practical Cron Job
Now let's replace the test job with something useful. We'll create a backup script that runs daily.
First, create a backup script:
mkdir -p ~/scripts
nano ~/scripts/daily-backup.sh
Add this content:
#!/bin/bash
# Daily backup script
BACKUP_DIR="$HOME/backups"
DATE=$(date +%Y-%m-%d)
SOURCE_DIR="$HOME/public_html"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Create compressed archive
tar -czf "$BACKUP_DIR/backup-$DATE.tar.gz" "$SOURCE_DIR" 2>&1 | logger -t daily-backup
# Delete backups older than 7 days
find "$BACKUP_DIR" -name "backup-*.tar.gz" -mtime +7 -delete
echo "Backup completed at $(date)" | logger -t daily-backup
Make it executable:
chmod +x ~/scripts/daily-backup.sh
Test it manually:
~/scripts/daily-backup.sh
Check that the backup was created:
ls -lh ~/backups/
Now schedule it in cron:
crontab -e
Remove the test job and add:
# Daily backup at 2:30 AM
30 2 * * * /home/yourusername/scripts/daily-backup.sh
Or using an absolute path with $HOME:
30 2 * * * $HOME/scripts/daily-backup.sh
Step 6: Handle Output and Logging
By default, cron emails output to the user. If email isn't configured, output is lost. Here's how to handle it:
Redirect to a Log File
30 2 * * * $HOME/scripts/daily-backup.sh >> $HOME/logs/backup.log 2>&1
This appends stdout and stderr to the log file.
Discard All Output
30 2 * * * $HOME/scripts/daily-backup.sh > /dev/null 2>&1
Use this only when you have logging inside the script itself.
Send Output via Email
Set the MAILTO variable at the top of your crontab:
[email protected]
30 2 * * * $HOME/scripts/daily-backup.sh
Requires a working mail transfer agent on the server.
Use Logger for System Logs
Inside your script:
echo "Backup started" | logger -t backup-script
View with:
journalctl -t backup-script
Step 7: Set Environment Variables
Cron jobs run with a minimal environment. The PATH variable typically includes only /usr/bin and /bin, which can cause "command not found" errors.
Define variables at the top of your crontab:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
SHELL=/bin/bash
HOME=/home/yourusername
30 2 * * * $HOME/scripts/daily-backup.sh
Or set them inside your script:
#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Rest of script
Use absolute paths for commands:
Instead of:
tar -czf backup.tar.gz /data
Use:
/usr/bin/tar -czf backup.tar.gz /data
Find command locations with:
which tar
Troubleshooting Cron Jobs
Check if Cron Is Running
sudo systemctl status cron
View Cron Logs
On most systems:
sudo grep CRON /var/log/syslog
On systems using journald:
sudo journalctl -u cron
Test Your Script Manually
Always run your script manually before scheduling:
bash -x ~/scripts/daily-backup.sh
The -x flag shows each command as it executes.
Common Issues
Script doesn't execute:
- Check file permissions (chmod +x script.sh)
- Verify the shebang line (#!/bin/bash)
- Use absolute paths for commands and files
- Check script ownership
Command not found:
- Set the PATH variable in your crontab or script
- Use absolute paths for all commands
Wrong user:
- Verify you edited the correct user's crontab
- Check with crontab -l and sudo crontab -l
Timing issues:
- Remember cron uses 24-hour time
- Check your server's timezone: timedatectl
- Test with a near-future time first
Silent failures: - Add logging to your script - Redirect output to a file - Check system logs
Best Practices
1. Always log script output so you can diagnose failures without waiting for the next execution.
2. Use locking mechanisms to prevent overlapping executions:
#!/bin/bash
LOCKFILE="/tmp/backup-script.lock"
if [ -f "$LOCKFILE" ]; then
echo "Script already running" | logger -t backup-script
exit 1
fi
touch "$LOCKFILE"
trap "rm -f $LOCKFILE" EXIT
# Your script logic here
3. Handle failures gracefully with proper exit codes and error messages.
4. Test in non-production first with a near-future schedule to verify behavior.
5. Document your cron jobs with comments in the crontab:
# Daily website backup at 2:30 AM
30 2 * * * $HOME/scripts/daily-backup.sh >> $HOME/logs/backup.log 2>&1
6. Monitor cron job execution using external monitoring tools or log analysis.
7. Rotate logs to prevent disk space issues:
# Rotate backup logs weekly
0 0 * * 0 find $HOME/logs -name "backup.log" -size +10M -exec mv {} {}.old \; -exec touch $HOME/logs/backup.log \;
Managing Multiple Cron Jobs
List all cron jobs for current user:
crontab -l
List for a specific user (as root):
sudo crontab -u username -l
Remove all cron jobs:
crontab -r
Use with caution—this deletes the entire crontab without confirmation.
Edit safely:
Always use crontab -e rather than editing crontab files directly. The -e option validates syntax before saving.
Conclusion
You now have a working cron job and understand the complete setup process from syntax to troubleshooting. Start with simple tasks like log cleanup or backups, test thoroughly, and gradually automate more of your server maintenance workflow.
Cron jobs are essential for maintaining healthy hosting environments—from WordPress maintenance windows to database backups, SSL renewals to log rotation. Master this tool and you'll spend less time on repetitive tasks and more time on what matters.
Remember to always test scripts manually before scheduling, use absolute paths, implement proper logging, and monitor execution. With these practices, cron becomes a reliable automation partner rather than a source of mysterious failures.
