Skip to content

30. Cron Job Scheduling

In Linux, the foundational tool for time-based job scheduling is Cron.

Cron is a time-based job scheduler in Unix-like operating systems. Users and administrators configure commands or shell scripts to run automatically at specific dates, times, or recurring intervals.

The scheduler runs as a persistent background daemon:

  • On Debian/Ubuntu: cron.service
  • On RHEL/AlmaLinux/Rocky: crond.service

The daemon wakes up every single minute (at :00 seconds), inspects scheduled job tables, checks if any job’s timestamp matches the current system time, executes eligible jobs in the background, and goes back to sleep.

Terminal window
# Check if the cron daemon is running
sudo systemctl status cron # or crond on RHEL

| Aspect | Manual Terminal Execution | Cron Execution | |||| | Environment | Inherits user’s full shell environment, $PATH, aliases | Minimal default environment (/usr/bin:/bin), no interactive profile | | Working Directory | Current working directory | User’s $HOME directory | | Standard Output (stdout) | Printed directly to terminal screen | Discarded or emailed to local mail spool unless explicitly redirected | | Interactive Prompts | Supports user input (read, [y/N] prompts) | Fails immediately if a command waits for interactive user input |

  • Daily/weekly compressed database backups and cloud sync.
  • Log pruning and log rotation.
  • Renewal of Let’s Encrypt SSL/TLS certificates via Certbot (certbot renew).
  • Health checks and watchdog monitoring scripts.
  • Periodic system updates (apt update or security scans).

Each user on a Linux system (including root) has their own private cron table called a Crontab. Individual user crontab files are stored in /var/spool/cron/crontabs/ (Debian/Ubuntu) or /var/spool/cron/ (RHEL), but they should never be edited directly by hand.

Use the crontab CLI tool:

Terminal window
# Edit the current user's crontab (opens in default editor: nano/vi)
crontab -e
# List the current user's active cron jobs
crontab -l
# Remove/delete all cron jobs for the current user (Use with caution!)
crontab -r
# As root: Edit another user's crontab (e.g. for the 'nginx' or 'deploy' service user)
sudo crontab -u deploy -e
# As root: View another user's crontab
sudo crontab -u deploy -l

A crontab entry consists of five time/date fields followed by the command to execute:

┌───────────── Minute (0 - 59)
│ ┌─────────── Hour (0 - 23, 24-hour clock)
│ │ ┌───────── Day of month (1 - 31)
│ │ │ ┌─────── Month (1 - 12 or JAN - DEC)
│ │ │ │ ┌───── Day of week (0 - 6, Sunday = 0 or 7, or SUN - SAT)
│ │ │ │ │
* * * * * /path/to/command argument1 argument2
  • * (Asterisk / Wildcard): Matches every possible value for that field (e.g., * in the hour field means “every hour”).
  • , (Comma / Value List): Specifies multiple discrete values (e.g., 1,15,30 in the minute field).
  • - (Hyphen / Range): Specifies an inclusive range of values (e.g., 1-5 in the day-of-week field means Monday through Friday).
  • / (Slash / Step Intervals): Skips values in steps (e.g., */15 in the minute field means “every 15 minutes”, */2 in hours means “every 2 hours”).
# Run every minute of every day
* * * * * /opt/scripts/heartbeat.sh
# Run every 15 minutes
*/15 * * * * /opt/scripts/check_queue.sh
# Run at 02:00 AM every night
0 2 * * * /opt/scripts/db_backup.sh
# Run at 04:30 AM every Monday through Friday
30 4 * * 1-5 /opt/scripts/weekday_report.sh
# Run at midnight on the 1st of every month
0 0 1 * * /opt/scripts/monthly_billing.sh
# Run at 03:00 AM every Sunday (0 = Sunday)
0 3 * * 0 /opt/scripts/full_system_backup.sh
# Run at 00:00, 06:00, 12:00, and 18:00 every day (every 6 hours)
0 0,6,12,18 * * * /opt/scripts/cert_check.sh
# (or using step notation):
0 */6 * * * /opt/scripts/cert_check.sh

Instead of 5 asterisks, cron supports predefined shortcut macros:

| Shortcut | Equivalent Expression | Meaning | |||| | @reboot | Run once at system startup | Perfect for starting background processes after boot | | @yearly / @annually| 0 0 1 1 * | Run once a year at midnight on January 1st | | @monthly | 0 0 1 * * | Run once a month at midnight on the first day | | @weekly | 0 0 * * 0 | Run once a week at midnight on Sunday | | @daily / @midnight | 0 0 * * * | Run once a day at midnight | | @hourly | 0 * * * * | Run once an hour at the start of the hour |

Example:

@reboot /opt/app/start_service.sh
@daily /opt/scripts/cleanup_tmp.sh

Beyond individual user crontabs, Linux provides system-wide directories for administrative automation.

The system-wide crontab file. Unlike user crontabs, it includes a mandatory User field between the timing expression and the command:

# m h dom mon dow user command
0 2 * * * root /usr/local/sbin/backup_all.sh

A modular directory where packages (like certbot, sysstat, or custom services) drop their own crontab files.

  • Files here use the same syntax as /etc/crontab (they must specify the username).
  • Modular files make software installation and removal clean without editing a single shared file.

Instead of writing timing expressions, you can simply drop executable shell scripts directly into these directories:

  • /etc/cron.hourly/: Scripts run every hour.
  • /etc/cron.daily/: Scripts run once a day (typically around 6:00 AM via anacron).
  • /etc/cron.weekly/: Scripts run once a week.
  • /etc/cron.monthly/: Scripts run once a month.

[!IMPORTANT] Scripts placed in /etc/cron.daily/ and similar folders must be executable (chmod +x), must include a proper shebang (#!/usr/bin/env bash), and should not have file extensions like .sh (Debian’s run-parts tool will ignore filenames with dots!).

The single most common reason why a script “works in my terminal but fails in cron” is the Environment.

In your interactive shell, $PATH includes /usr/local/bin, /home/user/.cargo/bin, /snap/bin, etc. In cron, $PATH is typically restricted to just /usr/bin:/bin. If your script calls docker, aws, node, or a script in /usr/local/bin, cron will fail with command not found.

Solutions:

  • Always use absolute paths to all executables in scripts and crontabs:
    Terminal window
    # BAD:
    python3 backup.py
    # GOOD:
    /usr/bin/python3 /opt/scripts/backup.py
  • Or explicitly define $PATH at the very top of your crontab:
    SHELL=/bin/bash
    PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
    HOME=/root
    0 2 * * * /opt/scripts/backup.sh

Cron executes commands in the user’s home directory. If your script relies on relative paths (e.g. ./config.json), it will fail unless the script explicitly cds to its directory:

Terminal window
0 3 * * * cd /opt/my-app && ./run_job.sh

Because cron jobs run disconnected from any terminal, standard output (stdout) and error output (stderr) have nowhere to display.

Always redirect both stdout and stderr to a log file:

# Append both stdout (1) and stderr (2) to a log file:
0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
# Suppress all output completely (discard to /dev/null):
0 2 * * * /opt/scripts/backup.sh > /dev/null 2>&1

When troubleshooting whether a job actually executed:

  • Ubuntu / Debian:
    Terminal window
    # Filter syslog for cron events
    sudo grep CRON /var/log/syslog
    # or using journalctl
    sudo journalctl -u cron -f
  • RHEL / Rocky / AlmaLinux:
    Terminal window
    # Dedicated cron log file
    sudo tail -f /var/log/cron

To simulate the exact stripped-down environment that cron will experience, run your script using env -i:

Terminal window
env -i HOME=/root PATH=/usr/bin:/bin /opt/scripts/backup.sh

If the script fails here, you have missing environment variables or non-absolute paths!

Cron runs with the full privileges of the user that owns the crontab. Securing cron is vital to preventing privilege escalation.

1. Restricting Access: /etc/cron.allow & /etc/cron.deny

Section titled “1. Restricting Access: /etc/cron.allow & /etc/cron.deny”

Administrators can control which users are permitted to create cron jobs:

  • If /etc/cron.allow exists, only users listed in this file can use crontab.
  • If /etc/cron.allow does NOT exist, everyone can use crontab except users listed in /etc/cron.deny.
  • Hardening Best Practice: Create an /etc/cron.allow containing only root and authorized administrative users:
    Terminal window
    sudo echo "root" > /etc/cron.allow
    sudo echo "deploy" >> /etc/cron.allow

If a cron job runs as root, the script it executes must be strictly write-protected. If a standard user can edit /opt/scripts/backup.sh, they can add a command to grant themselves root access:

Terminal window
# Ensure root owns the script and only root can write to it
sudo chown root:root /opt/scripts/backup.sh
sudo chmod 700 /opt/scripts/backup.sh

Avoid passing passwords or API tokens directly as CLI arguments in crontab (e.g. mysqldump -pSecretPassword). Any user on the system can see command arguments by running ps aux! Instead, store credentials in a root-readable config file (like ~/.my.cnf with chmod 600).

4. Detecting Malicious / Persistence Cron Jobs

Section titled “4. Detecting Malicious / Persistence Cron Jobs”

Attackers and rootkits frequently establish persistence by injecting jobs into crontab:

Terminal window
# Audit all user crontabs on the system
for user in $(cut -f1 -d: /etc/passwd); do
crontab -u "$user" -l 2>/dev/null && echo "=== Crontab for $user ==="
done
# Inspect system-wide cron folders
ls -la /etc/cron* /etc/cron.d/