Cron and Crontab Tutorial

cron is a time-based job scheduler in Unix-like operating systems that allows users to run scripts or commands at specified times and intervals. The crontab (cron table) is a file where users define these scheduled tasks.

1. Understanding the crontab Format

┌──────── Minute (0 - 59)
│ ┌────── Hour (0 - 23)
│ │ ┌──── Day of the month (1 - 31)
│ │ │ ┌── Month (1 - 12)
│ │ │ │ ┌── Day of the week (0 - 7, Sunday is both 0 and 7)
│ │ │ │ │
* * * * * command-to-execute
    

Examples

2. Managing crontab Jobs

3. Logging & Debugging

Check logs with:

grep CRON /var/log/syslog

Capture output of a cron job:

0 0 * * * /home/user/script.sh >> /home/user/cron.log 2>&1

In the above command, 2>&1 redirects standard error (stderr, file descriptor 2) to standard output (stdout, file descriptor 1). This ensures that both normal output and error messages are captured in the same log file.

4. Special @ Macros for Common Schedules

Example: @daily /home/user/cleanup.sh

5. Testing a Cron Job

Check if a cron job is set:

crontab -l | grep my_script.sh

Run the command manually to test:

/bin/bash /home/user/my_script.sh

6. Using cron with Environment Variables

Since cron does not load your usual shell environment, explicitly specify paths:

PATH=/usr/local/bin:/usr/bin:/bin
0 3 * * * /home/user/script.sh
    

7. Running Cron Jobs as Another User

To schedule a job for another user (as root):

sudo crontab -u username -e

Final Tip

Always test your cron job manually before scheduling it, and log the output for debugging! 🚀