A Linux monitoring cron job is a practical way to collect server evidence on a schedule without deploying a large observability platform. Cron is already available on most Linux systems, shell tools can expose the essentials, and plain files are easy to inspect during an incident. The difficult part is not scheduling a command; it is making collection trustworthy, secure, and useful over time.
A dependable setup must answer more than “did the script run?” It should identify service failures, capacity risk, sustained resource pressure, backup problems, and stale collection. It should also preserve enough history to distinguish a one-off spike from a trend that needs action.
Decide what the monitoring job must prove
Start with the services the server provides rather than a list of every available metric. Record the important applications, listening ports, filesystems, databases, backup jobs, certificates, and external dependencies. For each one, define what healthy, degraded, and unavailable mean.
A small web server might need to prove that:
- the public HTTPS endpoint returns the expected status and content;
- the web and database services are active;
- critical filesystems are mounted, writable, and have enough capacity;
- CPU, memory, swap, and I/O pressure remain within the normal range;
- the newest backup is recent and its destination has space;
- certificates and package-security maintenance have adequate lead time; and
- the monitoring result itself is current and complete.
This service-first approach keeps simple Linux monitoring focused. It also prevents a common false positive: the host responds to ping, but the application users need is unavailable.
Keep cron small and put logic in a script
A crontab should specify when a job runs, not contain a long chain of operational logic. Put the checks in a version-controlled script, test that script interactively, and let cron call one stable entry point. This makes quoting, error handling, review, and recovery much easier.
sudo install -d -m 0750 -o root -g adm /opt/server-health
sudo install -d -m 0750 -o root -g adm /var/lib/server-health
sudo install -d -m 0750 -o root -g adm /var/log/server-health
Use a dedicated unprivileged account when the checks do not require root. If a few commands need elevated access, grant only those commands through a tightly scoped sudoers rule rather than running the entire monitoring job as root.
Build a predictable collection script
The following Bash structure creates a timestamped report, records failures, prevents overlapping runs, and publishes the result atomically. Adapt the service names, URL, and mount list to the server.
#!/usr/bin/env bash
set -u -o pipefail
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH LC_ALL=C
state_dir=/var/lib/server-health
log_dir=/var/log/server-health
stamp=$(date -u +%Y%m%dT%H%M%SZ)
tmp_file=$(mktemp "$state_dir/.report.XXXXXX")
final_file="$state_dir/report-$stamp.txt"
error_count=0
exec 9>"$state_dir/collector.lock"
if ! flock -n 9; then
printf 'status=skipped reason=previous_run_active time=%s\n' "$stamp" \
>> "$log_dir/collector.log"
exit 1
fi
cleanup() { rm -f "$tmp_file"; }
trap cleanup EXIT
run_check() {
name=$1
shift
printf '\n[%s]\n' "$name" >> "$tmp_file"
if ! timeout 20s "$@" >> "$tmp_file" 2>&1; then
printf 'check_status=failed\n' >> "$tmp_file"
error_count=$((error_count + 1))
else
printf 'check_status=ok\n' >> "$tmp_file"
fi
}
printf 'collected_at_utc=%s\nhost=%s\n' "$stamp" "$(hostname -f)" > "$tmp_file"
run_check filesystem df -P -x tmpfs -x devtmpfs
run_check inodes df -Pi -x tmpfs -x devtmpfs
run_check memory free -w
run_check pressure sh -c 'cat /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io'
run_check failed_units systemctl --failed --no-legend
run_check web_health curl --fail --silent --show-error --max-time 15 \
--output /dev/null --write-out 'status=%{http_code} total=%{time_total}\n' \
https://example.com/health
printf '\ncollection_errors=%s\n' "$error_count" >> "$tmp_file"
chmod 0640 "$tmp_file"
mv "$tmp_file" "$final_file"
ln -sfn "$(basename "$final_file")" "$state_dir/latest.txt"
trap - EXIT
printf 'time=%s report=%s errors=%s\n' "$stamp" "$final_file" "$error_count" \
>> "$log_dir/collector.log"
exit "$(( error_count > 0 ))"
The fixed PATH and locale remove two common differences between an interactive shell and cron. flock prevents a slow run from colliding with the next one. Per-check timeouts stop a hung network or service command from blocking collection indefinitely, while atomic rename prevents readers from consuming a half-written report.
Add checks that match real failure modes
Generic host statistics are only the beginning of useful Linux server monitoring. Add checks that represent the way the service can actually fail.
Availability and response
Request an endpoint through the same route users depend on. Validate the HTTP status, response time, TLS certificate, and a small expected value where appropriate. A local process check and an external request provide different evidence; retain both for important services.
Disk capacity and inode use
Collect bytes, inodes, expected mounts, and writeability. Percentage used is not enough by itself. A filesystem at 70% and growing by 15 GB each day may be more urgent than one that has remained at 85% for months. Keep historical values so the review can estimate time remaining.
df -P -x tmpfs -x devtmpfs
df -Pi -x tmpfs -x devtmpfs
findmnt --json --bytes
findmnt --mountpoint /srv/application-data
CPU, memory, and I/O pressure
A single load-average sample rarely explains performance. Collect CPU use, runnable work, swap activity, pressure stall information, and block-device latency when available. Compare these signals with application response time before declaring a bottleneck.
vmstat 1 5
cat /proc/pressure/cpu
cat /proc/pressure/memory
cat /proc/pressure/io
iostat -xz 1 5
If iostat is optional on your systems, detect whether it exists and report “not installed” separately from “check passed.” Missing evidence should never silently become a healthy state.
Application, database, and backup checks
For MySQL, use a restricted monitoring account and a protected option file or socket-based local access. Track connection success, slow-query or latency movement, connection pressure, lock waits, and database storage growth. Do not put passwords in the crontab, process arguments, report, or email.
For backups, confirm the newest artifact timestamp, expected size range, destination capacity, verification result, and age of the last tested restore. A backup command returning zero is useful evidence, but it does not prove that the backup can be restored.
Schedule the Linux monitoring cron job safely
Create a file under /etc/cron.d or use the service account's crontab. Set the shell, path, and mail behavior explicitly. Redirect standard output and error so failures do not disappear.
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[email protected]
# Collect every 15 minutes with a small offset from the hour
7,22,37,52 * * * * monitor /usr/bin/timeout 2m /opt/server-health/collect.sh
# Create a weekly summary after the final Sunday collection
20 6 * * 1 monitor /usr/bin/timeout 5m /opt/server-health/weekly-summary.sh
Use the frequency the failure mode requires. Availability checks might run every few minutes, while filesystem growth, package status, and backup summaries may only need daily collection. Avoid placing every job exactly on the hour, when backups, log rotation, and other fleet-wide tasks may already compete for resources.
Be careful with percent signs in crontab command fields: cron treats an unescaped % specially. Keeping commands inside a script avoids this and many other quoting surprises.
Test in the same environment cron uses
A script that works in an administrator's shell can fail under cron because the working directory, environment variables, permissions, locale, home directory, or search path differ. Test with the intended account and a minimal environment.
sudo -u monitor env -i \
HOME=/var/lib/monitor \
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
LC_ALL=C \
/opt/server-health/collect.sh
echo $?
readlink -f /var/lib/server-health/latest.txt
sudo -u monitor test -r /var/lib/server-health/latest.txt
Also test deliberate failures: an unreachable URL, a timed-out command, a missing utility, a full destination, and a second overlapping run. Confirm that each condition produces a visible failure state and nonzero exit code rather than a misleading clean report.
Monitor the monitoring job
Cron launching a command does not prove the report arrived. Add a freshness check from outside the collection path. It should alert when the latest successful report is older than the expected interval plus a reasonable grace period.
latest=/var/lib/server-health/latest.txt
max_age=1800
now=$(date +%s)
modified=$(stat -c %Y "$latest" 2>/dev/null || printf 0)
age=$((now - modified))
if (( modified == 0 || age > max_age )); then
printf 'Monitoring data is stale: age=%s seconds\n' "$age" >&2
exit 1
fi
For stronger protection, run the freshness check from another host or service. A powered-off server cannot report that its own cron job stopped. At minimum, make stale data, failed checks, and missing hosts appear as unknown or failed rather than green.
Protect reports and control retention
Monitoring output can reveal hostnames, mount paths, software versions, listening services, and operational schedules. Keep reports outside the web root, limit file permissions, avoid collecting secrets, and encrypt data in transit when sending it elsewhere.
Define retention before files accumulate indefinitely. For example, keep detailed reports for 30 days and compact weekly summaries longer. Use logrotate for logs and a narrowly scoped cleanup rule for timestamped reports. Never use a broad deletion command against a path assembled from unchecked variables.
Turn snapshots into trends and actions
A folder of timestamped command output is evidence, but it is not yet a useful reporting system. Parse stable fields into a simple CSV, JSON document, or database table. Preserve the collection time, host, check status, units, and collector version alongside each measurement.
Review changes over seven and thirty days:
- disk and inode growth, including estimated time to a response threshold;
- application latency and error movement;
- CPU, memory, swap, and I/O pressure compared with the normal baseline;
- database latency, locks, connections, and storage growth;
- backup freshness, verification, and restore-test age; and
- failed or stale collection that reduces confidence in the report.
Separate urgent incidents from gradual risks. An unavailable service, missing mount, read-only filesystem, or expired certificate needs prompt escalation. Slow disk growth, latency drift, and recurring low-grade pressure belong in a weekly review with an owner and next action.
Linux monitoring cron job checklist
- Define the service and business failure modes before selecting commands.
- Keep scheduling in cron and operational logic in a reviewed script.
- Set an explicit path, locale, permissions, and working assumptions.
- Use a lock and both whole-job and per-check timeouts.
- Write reports atomically and return nonzero when checks fail.
- Protect credentials and monitoring output from unnecessary access.
- Test under the intended account with a minimal environment.
- Detect stale collection from outside the main job when possible.
- Retain structured history so snapshots become trends.
- Convert findings into owners, deadlines, and practical next steps.
Use cron as a reliable collection layer
A Linux monitoring cron job works well when it stays narrow: collect trustworthy evidence on schedule, expose failures clearly, and preserve enough history for comparison. It does not need to imitate a large dashboard. For developers and small businesses, a lightweight monitoring setup can provide better operational clarity when its checks map directly to services and its reports emphasize meaningful change.
DMCloud Architect turns Linux, MySQL, backup, and infrastructure evidence into concise weekly findings with trends and recommended actions. Explore Infrastructure Health Reporting for practical server visibility without another dashboard to watch.