Home/Engineer/Linux / Shell/Cron Job Scheduler: A Practi…
Linux / ShellBeginnerubuntucentosdebianmacoscroncrontablinux

Cron Job Scheduler: A Practical Guide

Covers crontab syntax, environment variable setup, and logging methods for automating recurring jobs.

Contents
  1. What is Cron?
  2. Basic crontab Usage
  3. Cron Syntax
  4. Environment Variable Setup
  5. Logging
  6. The /etc/cron.d Approach (Recommended)
  7. Common Mistakes

What is Cron?

A time-based job scheduler. Use it to automate recurring tasks such as backups, log cleanup, and report generation.


Basic crontab Usage

Bash
crontab -e        # Edit for the current user
crontab -l        # List currently registered jobs
crontab -r        # Delete all (caution)
sudo crontab -u www-data -e

Cron Syntax

CODE
# ┌─────────── minute (0-59)
# │  ┌────────── hour (0-23)
# │  │  ┌───────── day of month (1-31)
# │  │  │  ┌────────── month (1-12)
# │  │  │  │  ┌───────── day of week (0-7, 0 and 7 = Sunday)
# │  │  │  │  │
# *  *  *  *  *  command_to_run

Common Patterns

Bash
# Run every minute
* * * * * /opt/scripts/check.sh

# Backup every day at 2 AM
0 2 * * * /opt/scripts/backup.sh

# Every Monday at 9 AM
0 9 * * 1 /opt/scripts/weekly_report.sh

# Midnight on the 1st of every month
0 0 1 * * /opt/scripts/monthly_clean.sh

# Every 5 minutes
*/5 * * * * /opt/scripts/heartbeat.sh

# Weekdays (Mon–Fri) 8 AM–6 PM, every 30 minutes
*/30 8-18 * * 1-5 /opt/scripts/sync.sh

Environment Variable Setup

Bash
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=admin@example.com

0 2 * * * /opt/scripts/backup.sh

Logging

Bash
# Save stdout and stderr to a file
0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1

# Add a date timestamp
0 2 * * * echo "[$(date)] Backup started" >> /var/log/backup.log && /opt/scripts/backup.sh >> /var/log/backup.log 2>&1

Bash
# /etc/cron.d/myapp
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin

# Run daily at 3 AM as the deploy user
0 3 * * * deploy /opt/myapp/scripts/cleanup.sh >> /var/log/myapp-cron.log 2>&1

Common Mistakes

MistakeFix
Command path not specifiedUse an absolute path (/usr/bin/python3)
Missing environment variablesAdd source /etc/environment at the top of the script
No execute permissionchmod +x script.sh
Hard to verify resultsAppend >> /var/log/cron-job.log 2>&1
#cron#crontab#linux
Editorial note

AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us

Topic-related official docs (auto-linked · not per-claim sources)Linux man pages ↗

Questions & answers

Ask a question about this guide. We'll review and reply.