Cron Cheat Sheet

Here’s a cheat sheet for using Cron, a time-based job scheduler in Unix-like operating systems:

Cron Basics

  • Access the Cron Table:
    • crontab -e: Edit the current user’s crontab file.
  • List Cron Jobs:
    • crontab -l: Display the current user’s crontab entries.
  • Remove All Cron Jobs:
    • crontab -r: Remove all crontab entries.

Cron Syntax

Cron Format:

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6, Sunday = 0 or 7)
│ │ │ │ │
│ │ │ │ │
* * * * *

Wildcard Characters:

  • *: Matches any value.
  • ,: Specifies a list of values.
  • -: Specifies a range of values.
  • /: Specifies a step value.

Examples

  • Run a Job Every Hour:
    • 0 * * * * command
  • Run a Job Every Day at Midnight:
    • 0 0 * * * command
  • Run a Job Every Monday at 2:30 PM:
    • 30 14 * * 1 command
  • Run a Job Every 15 Minutes:
    • */15 * * * * command
  • Run a Job Every Weekday at 8:00 AM:
    • 0 8 * * 1-5 command

Special Strings

  • @reboot:
    • Run the job once after the system reboots.
  • @yearly or @annually:
    • Run the job once a year (0 0 1 1 *).
  • @monthly:
    • Run the job once a month (0 0 1 * *).
  • @weekly:
    • Run the job once a week (0 0 * * 0).
  • @daily or @midnight:
    • Run the job once a day (0 0 * * *).
  • @hourly:
    • Run the job once an hour (0 * * * *).

Miscellaneous

  • Redirect Output:
    • 0 * * * * command > /path/to/output.log 2>&1: Redirect both standard output and standard error to a file.
  • Logging Output to Syslog:
    • 0 * * * * command 2>&1 | /usr/bin/logger -t cronjob_tag: Log output to syslog.
  • Environment Variables:
    • SHELL=/bin/bash
    • PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
    • [email protected]
  • Prevent Email Notifications:
    • 0 * * * * command > /dev/null 2>&1: Suppress email notifications.

This cheat sheet provides a quick reference for creating and managing Cron jobs in Unix-like systems. Adjust the values based on your specific scheduling needs.