Example Scripts for Managing Scheduled Tasks on Linux

Recently, I have been working on modifying and migrating several scheduled task scripts, so I took the opportunity to review my knowledge of cron and systemd timers, summarizing it into a series of articles. Interested readers can click the links below to read the original articles. Thank you for your support.

Detailed Explanation of cron Timers on Linux

Detailed Explanation of systemd Timers on Linux

Detailed Comparison of systemd Timers and cron Timers

Can cron be used under systemd?

Why are cron scheduled tasks not executing? The 7 most common reasons and solutions

How to view the logs of scheduled tasks? journalctl vs /var/log/cron

Today, I will share some related scripts for managing scheduled tasks. However, I want to clarify that the scripts published here have been modified by me. I have removed some complex settings, context, variable declarations, etc., making them simpler and easier to understand. Some parts are just ideas or frameworks. If you really want to reuse them in your learning or work, you can improve upon this basis to suit your learning or work projects.

Automated Script Examples for Managing Scheduled Tasks

1. Example of a Task Monitoring Script

#!/bin/bash# cron_monitor.sh - Monitor the execution status of cron tasks
LOG_FILE="/var/log/cron_monitor.log"
ALERT_EMAIL="[email protected]"
# Check for failed tasks in the last 5 minutes
FAILED_TASKS=$(journalctl -u cron --since "5 minutes ago" | grep -c "returned status [^0]")
if [ $FAILED_TASKS -gt 0 ]; then    echo "$(date): Found $FAILED_TASKS failed cron tasks" >> $LOG_FILE
    # Send alert email    echo "Detected cron task execution failure, please address it promptly" | \
    mail -s "Cron Task Execution Failure Alert" $ALERT_EMAIL
fi

2. Performance Analysis of Scheduled Tasks

#!/bin/bash# performance_analyzer.sh
echo "=== Cron Task Performance Analysis Report ==="
echo "Generated on: $(date)"
# Statistics of task distribution by time
echo -e "\n=== Task Execution Time Distribution ==="
grep "$(date +%b\ %d)" /var/log/cron | grep CMD | \
cut -d' ' -f3 | cut -d: -f1 | sort | uniq -c | \
awk '{printf "%02d:00-%02d:59 executed %d times\n", $2, $2, $1}'
# Find the longest running tasks
echo -e "\n=== Possible Long-Running Tasks ==="
journalctl -u cron --since today -o verbose | \
grep -E "started|finished" | \
awk '{print $1, $2, $3, $NF}' | \
head -10

Log Management Script Examples

1. Quick Log Viewing Script

#!/bin/bash# cron_log_viewer.sh - A tool for quickly viewing cron logs
case $1 in    "today")        grep "$(date +%b\ %d)" /var/log/cron        ;;    "failed")        journalctl -u cron | grep -E "(FAILED|ERROR|returned status [^0])"        ;;    "user")        grep "($2)" /var/log/cron | tail -20        ;;    "script")        grep "$2" /var/log/cron | tail -20        ;;    *)        echo "Usage: $0 {today|failed|user <username>|script <scriptname>}"        ;;esac

2. Log Cleanup Script

#!/bin/bash# cleanup_cron_logs.sh
# Compress logs older than 7 days
find /var/log -name "*.log" -mtime +7 -exec gzip {} \;
# Delete compressed logs older than 30 days
find /var/log -name "*.log.gz" -mtime +30 -delete
# Clean up systemd journal (keep for 2 weeks)
journalctl --vacuum-time=2weeks
echo "Log cleanup completed: $(date)"

3. Log Status Check Script

#!/bin/bash# cron_health_check.sh
echo "=== Cron Service Health Check ==="
# Check cron service status
if systemctl is-active --quiet cron; then    echo "Cron service is running normally"
else    echo "Cron service is not running"
fi
# Check if there have been any tasks executed in the last hour
RECENT_JOBS=$(journalctl -u cron --since "1 hour ago" | grep CMD | wc -l)
echo "$RECENT_JOBS tasks executed in the last hour"
# Check the number of failed tasks
FAILED_JOBS=$(journalctl -u cron --since today | grep -c "returned status [^0]")
echo "Number of failed tasks today: $FAILED_JOBS"

4. Log Analysis Script Creation

#!/bin/bash# cron_log_analyzer.sh
echo "=== Cron Task Execution Statistics ==="
echo "Total executions today: $(grep "$(date +%b\ %d)" /var/log/cron | grep CMD | wc -l)"
echo "Number of failed tasks today: $(grep "$(date +%b\ %d)" /var/log/cron | grep "returned status [^0]" | wc -l)"
echo -e "\n=== Recently Executed Tasks ==="
grep "$(date +%b\ %d)" /var/log/cron | grep CMD | tail -5
echo -e "\n=== Summary of Errors Today ==="
grep "$(date +%b\ %d)" /var/log/cron | grep -E "(FAILED|ERROR|returned status [^0])"

Example Scripts for Managing Scheduled Tasks on Linux

Leave a Comment