Robin.te.Hofstee

Cron Jobs Cheatsheet

Robin te Hofstee7 min readViews4
Cron Jobs Cheatsheet

A concise reference for understanding and managing cron jobs, including syntax, special characters, common pitfalls, and troubleshooting tips.

Cron Jobs Cheatsheet

This cheatsheet provides a quick reference for working with cron jobs on Linux systems. Cron is a powerful tool for automating tasks, but understanding its intricacies is crucial for reliable scheduling. This document focuses on practical usage, troubleshooting, and common pitfalls, rather than a detailed theoretical explanation.

What is Cron and How Does it Work?

Cron is a daemon (a background process) that executes scheduled tasks. It runs continuously in the background, checking its configuration files (crontabs) against the current time. When a task's schedule matches the current time, crond (the cron daemon process) executes the associated command.

The crond daemon typically wakes up every minute (though the exact interval may vary depending on the system). It then iterates through the crontabs to see if any tasks are due to run.

Crontab Syntax

The core of cron is the crontab file, which defines the schedules for your tasks. Each line in a crontab represents a single job. The syntax is as follows:

*     *     *     *     *  command to execute
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- day of week (0 - 7) (Sunday=0 or 7)
|     |     |     +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- minute (0 - 59)

Here's a breakdown of each field:

FieldDescriptionExample
Minute0-590, 15, 30, 45
Hour0-230, 1, 2...23
Day of Month1-311, 15, 31
Month1-12 (or Jan, Feb, Mar...)1, 2, 3...12
Day of Week0-7 (0 and 7 are Sunday)0, 1, 2, 3, 4, 5, 6

Diagrammatic Representation:

                      +------- Month --------+
                      |                       |
                      |        1             |
                      |        2             |
                      |        3             |
                      +-----------------------+
                          |
                          |
                      +------- Day of Month --------+
                      |        15               |
                      |        31               |
                      +-----------------------+
                          |
                          |
                      +------- Day of Week --------+
                      |        0, 1, 2, 3, 4, 5, 6  |
                      +-----------------------+
                          |
                          |
                      +------- Hour --------+
                      |        0, 1, 2, ... 23 |
                      +-----------------------+
                          |
                          |
                      +------- Minute --------+
                      |        0, 15, 30, 45  |
                      +-----------------------+

Special Characters and Strings

  • *: Matches any value.
  • ,: Specifies a list of values, separated by commas. Example: 1,3,5
  • -: Specifies a range of values, separated by hyphens. Example: 1-5
  • /: Specifies a step value within a range. Example: */15 (every 15 minutes)

Special Strings:

StringDescription
@rebootRun once at system boot
@dailyRun once every day
@hourlyRun every hour
@weeklyRun every week
@monthlyRun every month
@yearlyRun every year
@annuallyRun once a year

Viewing, Editing, and Removing Crontabs

  • crontab -e: Opens the current user's crontab in a text editor (usually vi or nano).
  • crontab -l: Lists the current user's crontab.
  • crontab -r: Removes the current user's crontab (use with caution!).
  • crontab -u <user> -l: Lists the crontab for another user (requires appropriate permissions).

User vs. System Crontabs

  • User Crontabs: These are the crontabs associated with individual user accounts. They control tasks run under the user's context.
  • System Crontabs: These are located in /etc/crontab and /etc/cron.d/. They control tasks run as the root user (or a specific user defined in the file). Files in /etc/cron.d/ are interpreted as individual crontab files. /etc/crontab has a slightly different syntax and requires a final field for the user to run the job as.

Environment Variable Gotchas

Cron jobs run in a minimal environment. This often leads to issues:

  • Minimal PATH: The PATH variable is often not set, so scripts rely on commands being in the default PATH.
  • No Shell Profile Loaded: No shell profile files (e.g., .bashrc, .zshrc) are loaded.
  • Different Working Directory: The working directory is often /.

Example:

Let's say your script needs ls to list files. Without setting the PATH, cron won't find it.

#!/bin/bash
# This script will likely fail without setting the PATH
 
ls -l  # This may not work

Fix: Always explicitly set the PATH and define your working directory within the script.

#!/bin/bash
export PATH=$PATH:/usr/bin  # Add /usr/bin to the PATH
cd /home/user/my_project    # Set the working directory
ls -l  # This should now work

Logging and Debugging

  • Syslog: Cron often logs to syslog (usually /var/log/syslog or /var/log/messages).
  • Journalctl: Use journalctl -u cron to view cron logs.
  • Capturing Output: Redirect the output of your cron job to a file:
* * * * * /path/to/your/script.sh > /path/to/output.log 2>&1

Common Practical Examples

  • Nightly Backup: 0 0 * * * /path/to/backup_script.sh
  • Weekly Service Restart: 0 0 * * 0 /path/to/restart_service.sh
  • Temp Directory Clearing: 0 0 * * * /path/to/clear_temp_directory.sh
  • Every 15 Minutes: */15 * * * * /path/to/my_script.sh
  • Weekdays Only: Mon-Fri * * * * /path/to/my_script.sh

Troubleshooting Checklist

  • Check Logs: journalctl -u cron or /var/log/syslog
  • Verify Script Permissions: Make sure the script is executable.
  • PATH Issues: Explicitly set the PATH within the script.
  • Redirect Output: Capture the script's output to a file for debugging.
  • Check Cron Syntax: Double-check the crontab syntax for errors.
  • System Time: Ensure the system time is accurate.
  • User Permissions: Confirm the user running the cron job has the necessary permissions to execute the script and access any required files.

This cheatsheet provides a foundation for working with cron jobs. Experiment, test your configurations, and consult the documentation for your specific operating system for more advanced features and options.

Share this post
Robin te Hofstee

Written by Robin te Hofstee

Technology enthusiast with a deep love for programming. Sharing practical guides on React, Next.js, Linux and self-hosting.