Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Cron Heartbeat: What It Must Prove

· 5 min read · Home Tech

In this article
  1. What a Heartbeat Actually Proves
  2. How to Implement a Heartbeat in Python
  3. Choosing the Right Heartbeat Interval
  4. Common Problems and Misconceptions
  5. Alternatives to Heartbeats
  6. Frequently Asked Questions

A Python cron heartbeat is a periodic signal that proves your scheduled job is still alive and executing on time. It must prove three things: the process is running, it is not stuck, and it is completing its work within the expected interval. Without a heartbeat, a silently failing cron job can go unnoticed for days, weeks, or even months.

What a Heartbeat Actually Proves

A heartbeat is a liveness signal, not a correctness signal. It proves the process is running and making progress, but it does not prove the job did its work correctly. For example, a cron job that runs a database backup might send a heartbeat even if the backup file is empty. To prove correctness, you need a separate check that verifies the output—like checking file size or a success flag.

However, a heartbeat does prove several important things:

  • The scheduler is firing: cron (or your scheduler) is running and launching the job.
  • The process starts: the Python script can be executed without crashing on import or startup.
  • The process completes: the script reaches the end and sends the heartbeat—if it crashes mid-run, no heartbeat is sent.
  • It is roughly on time: the heartbeat arrives within the expected interval, meaning the job isn't stuck in a long loop or waiting on a deadlock.

But a heartbeat cannot prove that the job's logic is correct, that external services it depends on are healthy, or that the output is valid. Those need separate checks.

How to Implement a Heartbeat in Python

The simplest way is to send an HTTP request to a monitoring service (like Healthchecks.io, Cronitor, or a self-hosted endpoint) at the end of your script. Here's a minimal example using requests:

import requests

def run_job():
    # ... your actual work ...
    pass

if __name__ == "__main__":
    try:
        run_job()
        requests.post("https://your-monitor.com/ping/your-uuid", timeout=10)
    except Exception:
        # Optionally send a failure signal
        requests.post("https://your-monitor.com/fail/your-uuid", timeout=10)
        raise

Key points:

  • Send the heartbeat after the work completes, not at the start. A heartbeat at the start only proves the job started, not that it finished.
  • Use a timeout on the request so a hung network doesn't block your job.
  • Wrap the job in a try/except to send a failure signal on exceptions—this gives you immediate feedback.
  • Consider using a context manager or a decorator to avoid repeating the heartbeat code.

Choosing the Right Heartbeat Interval

The interval depends on how quickly you need to know about failures. A job that runs every 5 minutes might tolerate a 2-minute delay; a job that runs daily can tolerate a few hours. The general rule: set the allowed delay to be at least the job's normal runtime plus a buffer for scheduling jitter.

For example, if your job takes 30 seconds and runs every 10 minutes, a 2-minute allowed delay is reasonable. If your job occasionally takes 5 minutes due to heavy load, you need a larger delay to avoid false alerts.

Also consider the monitoring service's own check interval. If the service checks every minute, your max gap should be at least a few minutes so that a single missed check doesn't trigger a false alarm.

Common Problems and Misconceptions

Problem: False alerts from slow jobs. If your job sometimes runs longer than the allowed delay, you'll get false alerts. Solution: measure the actual runtime over a week and set the delay accordingly.

Problem: Heartbeat sent before work completes. Some developers put the heartbeat at the top of the script, which only proves the job started. Always send it at the end.

Problem: Ignoring exceptions. If your script crashes before reaching the heartbeat line, no signal is sent—which is good—but you might not know if the crash was transient. Sending a failure signal on exception gives you more detail.

Misconception: A heartbeat proves the job ran successfully. It only proves the script reached the end. A job can complete with errors (e.g., a failed API call that was caught) and still send a heartbeat. For correctness, add a separate check that validates the output.

Misconception: Heartbeats are only for cron. They work for any scheduled task: systemd timers, Kubernetes CronJobs, CI pipelines, and even manual runs.

Alternatives to Heartbeats

Heartbeats are not the only way to monitor cron jobs. Consider these alternatives:

  • Log monitoring: Parse logs for error patterns. This can catch failures but requires log aggregation and pattern matching.
  • Exit status checks: The cron daemon can email you on non-zero exit codes, but this only works if the script exits with a non-zero status on failure—and many scripts don't.
  • Output validation: Check that the job produced the expected output (e.g., a file exists and has content). This is more robust but requires knowing what "correct" looks like.
  • Dead man's switch: A heartbeat is a form of this—if the signal stops, an alert fires. You can also use a file timestamp that gets updated, but that's less reliable.

In practice, you'll often combine a heartbeat with output validation for the best coverage.

Frequently Asked Questions

What if my job runs longer than the expected interval? That's fine as long as the total time (runtime + delay) stays under the max gap. If your job regularly runs longer than the interval, increase the allowed delay or the interval itself.

Can I use a heartbeat for a job that runs only once a day? Yes. Set the expected interval to 1440 minutes (24 hours) and choose a delay that suits your tolerance—say 60 minutes. The max gap would be 1500 minutes (25 hours).

Should I send a heartbeat at the start or end of the job? End. A heartbeat at the start only proves the job started, which is less useful. If you want to know about long-running jobs, send a "start" signal and a "done" signal separately.

How many heartbeats should I send per run? Typically one, at the end. For long-running jobs, you might send periodic "still alive" signals to distinguish between a hung job and a slow one—but that adds complexity.

What happens if the monitoring service is down? Your heartbeat request will fail, and the service won't record it. To avoid false alerts, the monitoring service should have its own uptime, and your script should handle the failure gracefully (e.g., log it but don't crash).

Is a heartbeat enough for critical jobs? No. For critical jobs, combine a heartbeat with output validation and alerting on error logs. A heartbeat is a minimum, not a complete solution.