Standard cron syntax looks deceptively simple. You add 0 2 * * * /usr/bin/python3 /app/cleanup.py to your crontab and assume your database maintenance runs reliably every night at 2 AM.

Months later, you discover the script hasn't run in weeks. The cron daemon crashed, an environment variable was missing from cron's stripped-down path, or a process deadlocked on a database lock.

The core issue with standard cron is that failure looks identical to success: silence. A job that crashed, a job that hung indefinitely, and a job that never executed in the first place all leave zero trace unless you actively design around them.

The Fix: Implement a Dead Man's Switch

Traditional error handling relies on your application catching an error and raising an alert. But if the script crashes before execution, loses network connectivity, or enters an infinite loop, your error-handling code never runs.

Instead of waiting for an explicit failure signal, invert the pattern using a dead man's switch (heartbeat monitoring):

  1. Your cron job sends an HTTP request (a heartbeat ping) to an external monitoring service when it starts and finishes.
  2. The monitoring service expects this ping on a strict schedule (e.g., every 24 hours plus a 5-minute grace period).
  3. If the ping fails to arrive on time, the monitoring system triggers an alert via Slack, PagerDuty, or email.

With this approach, silence itself becomes the alert trigger.

Implementing Heartbeat Signals in Bash

You can convert any standard cron job into a monitored process using a wrapper script. Platforms like Healthchecks.io, Cronitor, or custom webhook handlers support heartbeat endpoints out of the box.

Here is a resilient Bash wrapper script pattern:

#!/usr/bin/env bash set -euo pipefail PING_URL="https://hc-ping.com/your-unique-uuid" # Signal job start to track execution duration curl -s -m 10 "${PING_URL}/start" > /dev/null || true # Run the target command and capture output if /usr/bin/python3 /app/cleanup.py >> /var/log/cron_cleanup.log 2>&1; then # Signal success curl -s -m 10 "${PING_URL}" > /dev/null else EXIT_CODE=$? # Signal explicit failure with exit status curl -s -m 10 "${PING_URL}/fail" --data-raw "Failed with exit code ${EXIT_CODE}" > /dev/null exit ${EXIT_CODE} fi 

This pattern guarantees three critical behaviors:

  • set -euo pipefail ensures script failures are caught immediately.
  • The /start signal enables the monitor to detect runs that take longer than expected.
  • If the script fails or hangs before reaching the success ping, the external service alerts you after the scheduled window expires.

Monitoring Jobs Directly in Code

If your scheduled task is written in Python, node, or another language, you can handle heartbeat pings directly inside your application logic.

import sys import requests MONITOR_URL = "https://hc-ping.com/your-unique-uuid" def run_scheduled_task(): # Send start signal try: requests.get(f"{MONITOR_URL}/start", timeout=5) except requests.RequestException: pass # Don't crash if monitoring ping fails try: # Perform actual job work here print("Processing batch jobs...") # Send completion ping on success requests.get(MONITOR_URL, timeout=5) except Exception as error: # Report explicit error to monitor requests.post(f"{MONITOR_URL}/fail", data=str(error), timeout=5) sys.exit(1) if __name__ == "__main__": run_scheduled_task() 

Best Practices for Hardening Background Jobs

Wiring up a heartbeat ping is the main requirement, but keeping your scheduled infrastructure reliable long-term requires a few extra operational checks:

Flag Long-Running Tasks

A stuck process consumes resources and prevents future executions if your script lacks concurrency locks. Ensure your monitoring tool flags runs that exceed their normal duration, or enforce execution timeouts using the OS-level timeout command:

timeout 300s /usr/bin/python3 /app/cleanup.py 

Preserve Exit Codes and Structured Logs

Never redirect cron output to /dev/null without writing to a log file or standard log collector. When a ping fails, you need stdout and stderr logs containing the exact exit code to diagnose why the script failed.

Ensure Safe Retries (Idempotency)

Before an incident occurs, verify whether your background job is safe to rerun manually. If a script fails halfway through sending invoices or running database migrations, running it a second time should not corrupt state or trigger duplicate actions.

Summary

The best infrastructure lets you know the moment it stops working, rather than forcing you to check logs manually. If you rely on a cron job for database backups, data synchronization, or report generation, add a dead man's switch to guarantee you are notified when it stops running.

About me

Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect on LinkedIn to discuss backend engineering, DevOps, or automation solutions.