crontab

crontab

·

3 min read

Structure of a crontab Entry

Each entry in a crontab file is made up of two main parts:

  1. Schedule specification: Defines when the job should run.

  2. Command to execute: Specifies the script, command, or executable to run.

Basic Syntax

bashCopy code* * * * * command_to_execute
FieldValue RangeDescription
Minute0-59The minute when the task runs.
Hour0-23The hour of the day (24-hour format).
Day of Month1-31The day of the month.
Month1-12The month of the year.
Day of Week0-6 (0 = Sunday)The day of the week.

Special Characters in crontab Fields

CharacterUsage
*Matches every value in the field.
,Separates multiple values.
-Specifies a range of values.
/Specifies step values (increments).

Examples with * and Other Characters

  1. Run every minute

     bashCopy code* * * * * /path/to/script.sh
    
    • Runs the command every minute of every hour, every day.
  2. Run at 5 AM daily

     bashCopy code0 5 * * * /path/to/script.sh
    
    • Runs the command at exactly 5:00 AM.
  3. Run on the 1st of every month at midnight

     bashCopy code0 0 1 * * /path/to/script.sh
    
    • Executes at midnight on the first day of each month.
  4. Run every Sunday at 2 PM

     bashCopy code0 14 * * 0 /path/to/script.sh
    
    • Executes at 2:00 PM every Sunday.
  5. Run every 5 minutes

     bashCopy code*/5 * * * * /path/to/script.sh
    
    • Executes every 5 minutes.
  6. Run every hour between 9 AM and 5 PM

     bashCopy code0 9-17 * * * /path/to/script.sh
    
    • Executes at the start of every hour from 9 AM to 5 PM.
  7. Run on weekdays (Monday to Friday) at 10:30 PM

     bashCopy code30 22 * * 1-5 /path/to/script.sh
    
    • Executes at 10:30 PM Monday through Friday.
  8. Run on the 15th and 30th of every month at noon

     bashCopy code0 12 15,30 * * /path/to/script.sh
    
    • Executes at 12:00 PM on the 15th and 30th of each month.

Special Macros in crontab

MacroEquivalent ScheduleDescription
@rebootRuns once at system startup.Example: Start a service on reboot.
@yearly0 0 1 1 *Runs once a year (midnight, Jan 1).
@monthly0 0 1 * *Runs once a month (midnight, 1st day).
@weekly0 0 * * 0Runs once a week (midnight, Sunday).
@daily0 0 * * *Runs once a day (midnight).
@hourly0 * * * *Runs every hour.

Common Issues and Troubleshooting

  1. cron Job Not Running

    • Ensure the script has execution permissions:

        bashCopy codechmod +x /path/to/script.sh
      
    • Check the cron logs:

        bashCopy codegrep CRON /var/log/syslog
      
  2. Environment Variables

    • cron may not have access to your user's environment variables. Explicitly set paths or source environment files in your script.
  3. Output Redirection

    • Redirect output to capture logs or silence errors:

        bashCopy code* * * * * /path/to/script.sh >> /path/to/logfile.log 2>&1