Cron is the Linux scheduler that runs commands automatically on a schedule: nightly backups, cache clearing, report generation, anything you would otherwise have to remember. Once you understand the five-field schedule, cron is simple and reliable. Here is how to use it.
The schedule syntax
A cron entry has five time fields followed by the command:
* * * * * command-to-run
| | | | |
| | | | day of week (0-6, Sunday = 0)
| | | month (1-12)
| | day of month (1-31)
| hour (0-23)
minute (0-59)
A few real examples:
0 3 * * * /usr/local/bin/backup.sh # every day at 3:00 AM
*/15 * * * * /usr/local/bin/check.sh # every 15 minutes
0 0 * * 0 /usr/local/bin/weekly.sh # midnight every Sunday
30 2 1 * * /usr/local/bin/monthly.sh # 2:30 AM on the 1st of the month
If the syntax is ever confusing, an online crontab helper translates a schedule into plain English.
Adding a job
Open your user's crontab:
crontab -e
Add a line using the syntax above, save, and it is scheduled. To see your current jobs:
crontab -l
Run jobs as the user that should own them. System-wide jobs go in /etc/cron.d/ or the /etc/cron.daily style folders.
The mistakes that make cron jobs fail
Cron failing silently is the classic frustration. The usual causes:
- No PATH: cron runs with a minimal environment, so a command that works in your shell may not be found. Use full paths (
/usr/bin/php, notphp). - Relative paths: cron does not start in your project folder. Use absolute paths for files, or
cdfirst. - No output, no clue: by default you never see errors. Log them so you can debug:
0 3 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
That >> ... 2>&1 appends both normal output and errors to a log file. It is the single best habit for cron.
A practical example: nightly database dump
0 3 * * * /usr/bin/mysqldump -u user -p'pass' dbname > /backups/db.sql 2>> /var/log/backup.log
This dumps the database every night and logs any errors. Pair it with off-site copies, see How to back up your server. (Note: a literal % in a crontab command must be escaped as \%.)
FAQ
Why does my cron job not run?
Almost always PATH or paths: cron uses a minimal environment, so use full paths to commands and files. Then add logging (>> file 2>&1) so you can see the actual error.
How do I run a job every few minutes?
Use the step syntax in the minute field: */5 * * * * runs every 5 minutes, */15 every 15.
Where do I see cron errors?
Nowhere, unless you log them. Append >> /path/to.log 2>&1 to the command so both output and errors are captured.
Automating maintenance on your own server? A Vastrox VPS gives you full root and cron access.