A Comprehensive Guide to Cron | Generated by AI

Home PDF

Cron is a powerful time-based job scheduler in Unix-like operating systems that allows users to schedule commands or scripts to run automatically at specified times or intervals. Here’s a complete guide to understanding and using cron effectively.

What is Cron?

Cron is a daemon (background service) that executes scheduled commands. It reads configuration files called “crontabs” (cron tables) to determine when to run particular commands. Cron is ideal for:

Cron Components

The Crontab File

The crontab (cron table) is a configuration file that specifies shell commands to run periodically. Each user can have their own crontab, and there’s also a system-wide crontab.

To edit your personal crontab:

crontab -e

To view your current crontab:

crontab -l

To remove your crontab:

crontab -r

Crontab Syntax

Each line in a crontab file represents a scheduled job and follows this format:

* * * * * command-to-execute
│ │ │ │ │
│ │ │ │ └─── Day of week (0-6, Sunday=0)
│ │ │ └───── Month (1-12)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)

Each position can contain:

After the five time/date fields comes the command to execute.

Common Cron Schedule Examples

Common Cron Schedule Examples

Basic Time Intervals

Cron Expression Description Example
* * * * * Run every minute * * * * * date >> /tmp/date_log.txt
*/5 * * * * Run every 5 minutes */5 * * * * /scripts/check_server.sh
0 * * * * Run at the start of every hour 0 * * * * /scripts/hourly_backup.sh
0 0 * * * Run at midnight daily 0 0 * * * /scripts/daily_backup.sh
0 0 * * 0 Run at midnight on Sundays 0 0 * * 0 /scripts/weekly_maintenance.sh
0 0 1 * * Run at midnight on the first day of each month 0 0 1 * * /scripts/monthly_report.sh
0 0 1 1 * Run at midnight on January 1 (yearly) 0 0 1 1 * /scripts/yearly_cleanup.sh

Specific Times

Cron Expression Description Example
30 8 * * 1-5 Run at 8:30 AM on weekdays (Monday-Friday) 30 8 * * 1-5 /scripts/workday_start.sh
0 18 * * 1-5 Run at 6:00 PM on weekdays 0 18 * * 1-5 /scripts/workday_end.sh
0 9-17 * * * Run at the start of every hour during business hours (9 AM - 5 PM) 0 9-17 * * * /scripts/hourly_check.sh
0 0,12 * * * Run at midnight and noon 0 0,12 * * * /scripts/twice_daily.sh

Multiple Time Specifications

Cron Expression Description Example
0 */4 * * * Run every 4 hours 0 */4 * * * /scripts/periodic_task.sh
0 4,16 * * * Run at 4:00 AM and 4:00 PM 0 4,16 * * * /scripts/twice_daily_at_4.sh
15,45 * * * * Run at 15 and 45 minutes past every hour 15,45 * * * * /scripts/quarter_hourly.sh

Special Time Specifications

Cron Expression Description Example
@reboot Run once at startup @reboot /scripts/startup_task.sh
@yearly or @annually Run once a year (0 0 1 1 *) @yearly /scripts/annual_task.sh
@monthly Run once a month (0 0 1 * *) @monthly /scripts/monthly_task.sh
@weekly Run once a week (0 0 * * 0) @weekly /scripts/weekly_task.sh
@daily or @midnight Run once a day (0 0 * * *) @daily /scripts/daily_task.sh
@hourly Run once an hour (0 * * * *) @hourly /scripts/hourly_task.sh

Complex Examples

Cron Expression Description Example
0 0 */2 * * Run at midnight every other day 0 0 */2 * * /scripts/every_other_day.sh
0 3 * * 1,3,5 Run at 3:00 AM on Monday, Wednesday, and Friday 0 3 * * 1,3,5 /scripts/mwf_task.sh
30 23 * * 2,4 Run at 11:30 PM on Tuesday and Thursday 30 23 * * 2,4 /scripts/tue_thu_night.sh
45 11 1-7 * * Run at 11:45 AM during the first week of each month 45 11 1-7 * * /scripts/first_week_task.sh
0 20 * 10,11,12 * Run at 8:00 PM during October, November, and December 0 20 * 10,11,12 * /scripts/q4_evening_task.sh
0 9-17/2 * * 1-5 Run every other hour during business hours on weekdays 0 9-17/2 * * 1-5 /scripts/biweekly_workday.sh

Special Cron Strings

Cron also supports several special strings for common time specifications:

Handling Output and Errors

By default, cron sends the output of commands via email to the user who owns the crontab. You can redirect output to a file or discard it:

# Append output to a log file
30 5 * * * /path/to/script.sh >> /path/to/logfile.log 2>&1

# Discard all output
0 12 * * * /path/to/script.sh > /dev/null 2>&1

Environment Variables in Cron

Cron jobs run with a minimal environment, which can cause scripts to fail. You can set variables in the crontab file:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
SHELL=/bin/bash
MAILTO=your-email@example.com

# Jobs will now use these environment variables
0 5 * * * /path/to/script.sh

Cron Security Considerations

  1. Use absolute paths for all commands and scripts
  2. Restrict crontab file permissions
  3. Use the principle of least privilege when setting up cron jobs
  4. Log and monitor cron job output for debugging
  5. Consider using a dedicated user for sensitive cron jobs

Troubleshooting Cron Jobs

Common issues with cron jobs include:

  1. Job doesn’t run: Check permissions and paths
  2. Timing issues: Verify the time format is correct
  3. Environment problems: Ensure necessary variables are set
  4. Script errors: Test the script manually first

Check system logs for cron-related messages:

grep CRON /var/log/syslog

Cron Alternatives

While cron is prevalent, there are alternatives:

Advanced Cron Usage

Running Jobs As Different Users

To edit the crontab for another user (requires root):

sudo crontab -u username -e

System-Wide Crontabs

System-wide cron jobs can be added to:

The syntax for system crontabs includes an additional user field:

* * * * * user command-to-execute

Running Cron Jobs with Specific Environment

Create a wrapper script to set up the environment before running your actual command:

#!/bin/bash
source /home/user/.profile
cd /path/to/working/directory
/path/to/actual/command

Then call this wrapper script from cron.

Best Practices for Cron Jobs

  1. Document your cron jobs: Add comments to explain what each job does
  2. Use descriptive script names: Makes maintenance easier
  3. Log outputs: Save job outputs for troubleshooting
  4. Monitor job execution: Implement monitoring for critical jobs
  5. Handle failures gracefully: Add error handling to your scripts
  6. Use lockfiles: Prevent overlapping execution when jobs take longer than expected
  7. Consider time zones: Be aware of system time zone settings

By following this guide, you should be able to effectively set up, manage, and troubleshoot cron jobs on your Unix-like system.


Back 2025.04.02 Donate