How to Schedule Tasks in Linux Using Cron
To schedule a task in Linux, use the
cron service by adding commands to your crontab file with a specific time pattern. The crontab -e command opens the editor to create or edit scheduled tasks that run automatically at set times.Syntax
The basic syntax for scheduling a task with cron in Linux is:
minute hour day_of_month month day_of_week command
Each field defines when the command runs:
- minute: 0-59
- hour: 0-23
- day_of_month: 1-31
- month: 1-12
- day_of_week: 0-7 (0 or 7 is Sunday)
- command: the script or command to run
Use * to mean "every" for any field.
bash
*/5 * * * * /path/to/script.shExample
This example schedules a script to run every day at 7:30 AM.
bash
30 7 * * * /home/user/backup.sh
Output
No output is shown immediately; the script runs automatically at 7:30 AM daily.
Common Pitfalls
Common mistakes when scheduling tasks in Linux include:
- Not using full paths for commands or scripts, causing failures.
- Editing the wrong user's crontab or forgetting to save changes.
- Not setting executable permissions on scripts.
- Assuming environment variables like
PATHare the same as your shell.
Always test your commands manually before scheduling.
bash
# Wrong: * * * * * backup.sh # Right: * * * * * /home/user/backup.sh
Quick Reference
| Field | Allowed Values | Description |
|---|---|---|
| minute | 0-59 | Minute of the hour |
| hour | 0-23 | Hour of the day |
| day_of_month | 1-31 | Day of the month |
| month | 1-12 | Month of the year |
| day_of_week | 0-7 | Day of the week (0 or 7 is Sunday) |
| command | Any valid command | Script or command to run |
Key Takeaways
Use
crontab -e to edit your scheduled tasks safely.Specify exact times using five fields before the command in crontab.
Always use full paths for scripts and commands in cron jobs.
Test commands manually before scheduling to avoid silent failures.
Remember cron runs with a limited environment; set variables if needed.