What it is
A cron daemon utility for scheduling commands and scripts to run automatically at specified intervals.
Installation
Cron is typically pre-installed on most Linux and macOS systems.
Linux:
sudo apt update && sudo apt install cron # Debian/Ubuntu
sudo yum install cronie # CentOS/RHEL/Fedora
macOS: Cron is included by default.
Windows: Windows Task Scheduler is the equivalent. Cron for Windows is available but not standard.
Core Concepts
- Cron Job: A scheduled task.
- Crontab: A file that contains the schedule of cron jobs to be run. Each user can have their own crontab file.
- Cron Daemon: The background process that reads crontab files and executes jobs.
Commands / Usage
Managing Crontab Files
crontab -eEdit the current user’s crontab file. If no crontab exists, a new one is created.crontab -lList the current user’s crontab entries.crontab -rRemove the current user’s crontab file.crontab -iRemove the current user’s crontab file with a confirmation prompt.crontab -u <username> -eEdit the crontab file for a specific user (requires root privileges).crontab -u <username> -lList the crontab entries for a specific user (requires root privileges).crontab -u <username> -rRemove the crontab file for a specific user (requires root privileges).
Cron Syntax
A cron job line has five time-and-date fields, followed by the command to be executed.
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday;
│ │ │ │ │ 7 is also Sunday on some systems)
│ │ │ │ │
* * * * * command_to_execute
Special Characters:
*(Asterisk): Wildcard. Matches any value.* * * * *: Run every minute.
,(Comma): List separator. Specifies a list of values.0,15,30,45 * * * *: Run at minutes 0, 15, 30, and 45 of every hour.0 9,17 * * 1-5: Run at 9 AM and 5 PM on weekdays (Monday to Friday).
-(Hyphen): Range of values.0 9-17 * * 1-5: Run at the start of every hour from 9 AM to 5 PM on weekdays.
/(Slash): Step values.*/15 * * * *: Run every 15 minutes.0 */2 * * *: Run every 2 hours, on the hour.
Predefined Schcedules (Shortcuts):
These are convenient shortcuts for common schedules.
@rebootRun once after reboot.@reboot /home/user/scripts/startup.sh
@yearlyor@annuallyRun once a year. Equivalent to0 0 1 1 *.@yearly /home/user/scripts/yearly_report.sh
@monthlyRun once a month. Equivalent to0 0 1 * *.@monthly /home/user/scripts/monthly_backup.sh
@weeklyRun once a week. Equivalent to0 0 * * 0.@weekly /home/user/scripts/weekly_cleanup.sh
@dailyor@midnightRun once a day. Equivalent to0 0 * * *.@daily /home/user/scripts/daily_sync.sh
@hourlyRun once an hour. Equivalent to0 * * * *.@hourly /home/user/scripts/hourly_check.sh
Example Crontab Entries:
- Run a script every day at 2:30 AM:
30 2 * * * /usr/local/bin/my_daily_script.sh - Run a backup script every Sunday at 11:00 PM:
0 23 * * 0 /opt/scripts/backup.sh - Run a command every 10 minutes:
*/10 * * * * /usr/bin/ping -c 1 google.com > /dev/null - Run a command at 8 AM, 12 PM, and 4 PM on weekdays:
0 8,12,16 * * 1-5 /usr/bin/send_notification.sh - Run a cleanup script on the 1st of every month at 3 AM:
0 3 1 * * /home/user/scripts/cleanup.sh
Environment Variables and PATH:
Cron jobs run with a very minimal environment. The PATH variable is often limited. It’s best practice to:
- Use absolute paths for commands and scripts.
- Source your environment if your script depends on specific variables.
Or define variables within the crontab:0 * * * * . /home/user/.bashrc; /home/user/scripts/my_script_with_env.shPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/user/bin MY_VAR="some_value" 0 * * * * /home/user/scripts/my_script.sh
Output Redirection:
By default, cron sends the output (stdout and stderr) of a job via email to the user who owns the crontab. To manage this:
- Discard all output:
(* * * * * /path/to/command > /dev/null 2>&1>/dev/nullredirects stdout,2>&1redirects stderr to stdout). - Log output to a file:
(Appends output to the log file).* * * * * /path/to/command >> /var/log/my_command.log 2>&1
Common Patterns
- Running a script daily at midnight:
@daily /home/myuser/scripts/daily_task.sh - Running a script every 5 minutes:
*/5 * * * * /home/myuser/scripts/frequent_task.sh - Running a script on the first day of the month at 5 AM:
0 5 1 * * /home/myuser/scripts/monthly_report.sh - Running a script at specific times on weekdays:
0 9,13,17 * * 1-5 /home/myuser/scripts/work_hours_alert.sh - Running a script on reboot and logging output:
@reboot /home/myuser/scripts/startup_service.sh >> /var/log/startup.log 2>&1 - Running a command that requires a specific PATH:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 0 3 * * * /usr/local/bin/my_custom_tool --process
Gotchas
- Environment Variables: Cron jobs run with a minimal set of environment variables.
PATHis particularly limited. Always use absolute paths for commands and scripts, or explicitly set thePATHin your crontab. - Permissions: Ensure the user whose crontab you are editing has the necessary permissions to execute the script and access any files/directories it uses.
- Working Directory: Cron jobs do not necessarily run from your home directory. Scripts might fail if they expect to be run from a specific directory. Use
cdwithin your script or specify the full path to files.* * * * * cd /home/user/myproject && /usr/bin/python manage.py run_scheduled_tasks - Output Email: By default, any output (stdout or stderr) from a cron job is emailed to the user. If you don’t want these emails, redirect output to
/dev/nullor a log file. - Special Characters: Be careful with characters like
%. In a crontab,%is treated as a newline, and everything after it is passed as standard input to the command. If you need a literal%, escape it with\%.# This will run 'echo hello%world' * * * * * echo hello\%world # This will echo 'hello' and pass 'world' as stdin to echo * * * * * echo hello%world - System Time: Cron uses the system’s clock. Ensure your system time is accurate, especially if scheduling time-sensitive tasks.
- Root Crontab: Editing the root crontab (
sudo crontab -e) requires root privileges and affects system-wide tasks. Be cautious. @rebootExecution Time:@rebootjobs run after the cron daemon starts, which might be before all other system services are fully initialized. If your job depends on other services, you might need a delay or a more robust startup mechanism.