Linux & Servers guides, explanations and reader checklists on whilenetworking.com

Automating Daily System Health Checks with Custom Systemd Timer Units and Email Alerts

In modern server management, relying on manual scripts run ad-hoc is a recipe for missed alerts and undetected outages. Whether you are a student managing a…

In modern server management, relying on manual scripts run ad-hoc is a recipe for missed alerts and undetected outages. Whether you are a student managing a lab VM or an engineer maintaining production infrastructure, automating system health checks ensures consistency and reliability. This guide demonstrates how to build a robust monitoring solution using systemd timers, custom shell scripts, and email notifications. By leveraging the native scheduling capabilities of Linux, you can create a lightweight, dependency-free monitoring agent that runs daily without consuming excessive resources.

Understanding the Architecture: Systemd Timers and Scripts

Before writing any code, it is essential to understand the components involved. systemd is the init system used by most modern distributions like Ubuntu, Debian, Fedora, and RHEL. It manages services (daemons) and timers (scheduled events). A timer unit triggers a service unit at a specific interval. In this scenario, we will create a custom script that performs health checks (disk usage, memory, SSH status) and then configure a timer to execute it every 24 hours.

The architecture consists of three parts:
1. The Script: A shell script containing the logic for checking system metrics.
2. The Service Unit: A definition file that tells systemd how to run the script once triggered.
3. The Timer Unit: A definition file that schedules when the service should start.

This approach is superior to cron for server environments because it integrates directly into the system’s dependency management, allowing for better logging and control over execution states.

Creating the Health Check Script

We will create a script named health-check.sh located in /usr/local/bin/. This directory is standard for local binaries and ensures the file persists across package upgrades. Open your terminal and create the file:

sudo nano /usr/local/bin/health-check.sh

Inside the editor, paste the following logic. Each command checks a specific metric and logs the result to /var/log/system-health.log. We also include a trap handler to ensure the log file is closed properly even if the script crashes.

#!/bin/bash

# Define variables for paths and timing
LOG_FILE="/var/log/system-health.log"
DATE=$(date +"%Y-%m-%d %H:%M:%S")

# Ensure log directory exists and has correct permissions
if [ ! -d "/var/log" ]; then
    echo "[$DATE] ERROR: /var/log does not exist." | tee -a "$LOG_FILE"
    exit 1
fi

# Function to write logs safely
log_message() {
    echo "[$DATE] $1" >> "$LOG_FILE"
}

# Check 1: Disk Usage on Root Partition
log_message "Starting disk usage check..."
DISK_USAGE=$(df -h / | tail -1 | awk '{print $5}')
if [ "${DISK_USAGE%[^0-9]*}" -ge 90 ]; then
    log_message "WARNING: Root partition usage is critical (${DISK_USAGE})."
else
    log_message "INFO: Root partition usage is healthy (${DISK_USAGE})."
fi

# Check 2: Memory Usage (Simple heuristic)
log_message "Checking memory..."
MEM_INFO=$(free -h | grep Mem | awk '{print $3 "/" $2}')
log_message "INFO: Memory status: ${MEM_INFO}"

# Check 3: SSH Service Status
log_message "Checking SSH service..."
if systemctl is-active --quiet ssh; then
    log_message "INFO: SSH service is active."
else
    log_message "CRITICAL: SSH service is inactive!"
fi

# Check 4: Web Server (Nginx/Apache) Status - Example for Nginx
log_message "Checking web server..."
if systemctl is-active --quiet nginx; then
    log_message "INFO: Nginx is active."
else
    log_message "WARNING: Nginx is not active."
fi

log_message "Health check completed successfully."

Save the file and make it executable:

sudo chmod +x /usr/local/bin/health-check.sh

Note: This script uses standard Linux commands (df, free, systemctl). It does not require root privileges to run but writes logs to a directory requiring root access. The script assumes the host is running systemd (Linux). Windows or macOS users would need alternative schedulers like Task Scheduler or cron.

Configuring the Systemd Service Unit

Next, we define how systemd should handle the script. Create a service unit file at /etc/systemd/system/health-check.service. This file defines the type of service (one-shot) and the command to execute.

sudo nano /etc/systemd/system/health-check.service

Insert the following configuration:

[Unit]
Description=Daily System Health Check Script
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/health-check.sh
StandardOutput=journal
StandardError=journal
# Restart policy is not needed for oneshot, but good practice to define timeout
TimeoutStartSec=120

[Install]
WantedBy=multi-user.target

The [Service] section specifies Type=oneshot, indicating the script runs once and exits. The ExecStart line points to our script path. We also direct output to the journal so logs are accessible via journalctl.

Setting Up the Timer Unit

Now we create the timer that triggers the service daily. Create a file at /etc/systemd/system/health-check.timer:

sudo nano /etc/systemd/system/health-check.timer

Insert this configuration:

[Unit]
Description=Run health check every day

[Timer]
OnBootSec=5min
OnUnitActiveSec=1d
AccuracySec=1h
Persistent=true

[Install]
WantedBy=timers.target

Key parameters explained:
* OnBootSec=5min: Run the check 5 minutes after boot.
* OnUnitActiveSec=1d: Run every 24 hours from the last execution.
* Persistent=true: If the system reboots before the scheduled time, the timer will catch up and run immediately upon boot.

Enabling and Testing the Automation

Once the files are created, reload the systemd manager configuration to recognize the new units:

sudo systemctl daemon-reload

Enable the timer so it starts automatically on boot:

sudo systemctl enable health-check.timer

Start the timer immediately to test without waiting for the next day:

sudo systemctl start health-check.timer

To verify the status, check if the service is scheduled:

systemctl list-timers | grep health-check

You should see an entry showing the next activation time. To manually trigger the check now (useful for debugging):

sudo systemctl start health-check.service

Check the logs to confirm success:

journalctl -u health-check.service -n 20 --no-pager

Email Alerts and Common Troubleshooting

Currently, our script only writes to a log file. To receive email alerts, we can modify the script to send an email using mail (if installed) or curl to an SMTP server. For simplicity in many lab environments, assuming mailx is available:

# Add this to the end of health-check.sh if critical errors occur
if [ $? -ne 0 ]; then
    echo "System Health Check Failed" | mail -s "Alert: System Issues Detected" admin@example.com
fi

Common Errors and Fixes:
* Permission Denied: If you see Permission denied when running the script, ensure the file is executable (chmod +x) and that /var/log allows writes.
* Timer Not Starting: Check if systemctl list-timers shows nothing. Ensure daemon-reload was run after creating files.
* Script Syntax Errors: Always check syntax with bash -n /usr/local/bin/health-check.sh before installing.
* Missing Dependencies: If commands like df or free are missing, install them via your package manager (e.g., apt-get install psmisc).

Student Practice Task and Industry Application

Student Task: Set up a virtual machine using VirtualBox with Ubuntu Server. Install Nginx manually. Create the health check script to monitor disk space and ensure Nginx is running. Configure the systemd timer to run every 6 hours instead of daily. Write a log rotation rule in /etc/logrotate.d/ specifically for your health log.

Industry Application: In production environments, this pattern scales. Instead of sending emails (which can be unreliable), teams often push alerts to Slack, PagerDuty, or monitoring platforms like Prometheus/Grafana using similar script logic. The core principle remains the same: decouple the logic of the check from the scheduling mechanism using systemd. This separation allows for easier maintenance, rollback of scripts, and precise control over execution frequency without cluttering cron jobs.

By mastering this workflow, you gain a foundational skill in Linux system administration that applies across almost all enterprise environments.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.