Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Linux Cron Job Scheduling and Management

Tech May 18 3

Cron Service Fundamentals

Cron is a time-based job scheduler in Unix-like operating systems. The crond daemon runs in the background and executes scheduled commands at specified intervals.

# Check if cron service is running
ps aux | grep cron | grep -v 'grep'

# Verify cron service status across runlevels
chkconfig crond --list

# Monitor cron execution logs
tail -f /var/log/cron

The cron daemon checks for scheduled tasks every minute. Logs are maintained at /var/log/cron.

System-Level Cron Jobs

System cron jobs are defined in /etc/crontab and manage essential system maintenance tasks:

# /etc/crontab structure
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

Common system maintenance scripts:

  • /etc/cron.daily/: logrotate, tmpwatch, package management
  • /etc/cron.weekly/: database updates, system checks
  • /etc/cron.monthly/: comprehensive system maitnenance

User-Level Cron Cofniguration

Individual users can create personal cron jobs using crontab:

# Edit current user's cron jobs
crontab -e

# List scheduled tasks
crontab -l

# Manage another user's cron jobs (root only)
crontab -u username -e

User cron files are stored in /var/spool/cron/username.

Cron Time Syntax

Cron uses a five-field time specification:

* * * * * command_to_execute
│ │ │ │ └── Day of week (0-7, 0=Sunday)
│ │ │ └──── Month (1-12)
│ │ └────── Day of month (1-31)
│ └──────── Hour (0-23)
└────────── Minute (0-59)

Time pattern examples:

# Daily at 2:00 AM
00 02 * * * /path/to/command

# Monthly on 1st at 2:00 AM
00 02 1 * * /path/to/command

# Every Sunday at 2:00 AM
00 02 * * 0 /path/to/command

# Every 5 minutes
*/5 * * * * /path/to/command

# Specific days (1st, 5th, 8th) at 2:00 AM
00 02 1,5,8 * * /path/to/command

# Range of days (1st through 8th) at 2:00 AM
00 02 1-8 * * /path/to/command

Practical Example: Automated Backup System

Create a daily backup script for the /etc directory:

Backup Script Implementation

#!/bin/bash
# backup_etc.sh - Automated /etc directory backup

BACKUP_DIR="/var/backup"
TIMESTAMP=$(date +%Y-%m-%d)
ARCHIVE_NAME="${TIMESTAMP}_etc_backup.tar.gz"

# Ensure backup directory exists
if [ ! -d "$BACKUP_DIR" ]; then
    mkdir -p "$BACKUP_DIR"
fi

# Create compressed backup
tar -czf "${BACKUP_DIR}/${ARCHIVE_NAME}" /etc > /dev/null 2>&1

# Remove backups older than 5 days
find "$BACKUP_DIR" -name "*_etc_backup.tar.gz" -mtime +5 -delete

Make the script executable:

chmod +x /root/backup_etc.sh

Schedule the Backup Task

Add to crontab:

# Edit root's crontab
crontab -e

# Add daily backup at 4:00 AM
0 4 * * * /root/backup_etc.sh

Testing the Implementation

# Test script manually
/root/backup_etc.sh

# Verify backup creation
ls -la /var/backup/

# Check cron execution logs
grep "backup_etc.sh" /var/log/cron

Advanced Cron Techniques

Second-Level Execution

Cron doesn't natively support second granularity, but you can implement it:

# Execute command every 10 seconds
* * * * * /path/to/command
* * * * * sleep 10; /path/to/command
* * * * * sleep 20; /path/to/command
* * * * * sleep 30; /path/to/command
* * * * * sleep 40; /path/to/command
* * * * * sleep 50; /path/to/command

Continuous Execution with Sleep

For frequent periodic tasks, use a while loop:

#!/bin/bash
# continuous_monitor.sh
while true
do
    # Your command here
    sleep 10

done

Anacron: Missed Job Recovery

Anacron handles jobs that may have been missed during system downtime:

# /etc/anacrontab configuration
1       65      daily_jobs    run-parts /etc/cron.daily
7       70      weekly_jobs   run-parts /etc/cron.weekly
30      75      monthly_jobs  run-parts /etc/cron.monthly

The format is: frequency delay job_identifier command where frequency is in days, delay is in minutes.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.