Heartbeat monitoring for Python scripts
On this page
To add heartbeat monitoring to a Python script, send an HTTP request to a heartbeat URL when the script starts, another when it finishes, and a failure with the error message if it raises. Python's standard library can do it with urllib.request, so there's nothing to install. An outside monitor then alerts you when the finish doesn't arrive on time, when the script fails, or when it starts and never finishes.
The one-line version, for scripts run by cron
If cron or another scheduler already runs the script, you don't need to touch the Python at all. Ping after the script, with its exit status:
0 3 * * * /usr/bin/python3 /opt/jobs/report.py; curl -fsS -m 10 --retry 3 https://stallbell.com/p/TOKEN/$?
$? is the exit status of the script. Python's docs say an exit status of zero is successful termination and any nonzero value is abnormal, so /0 reports success and /1 to /255 report a failure with that code. A script that ends with sys.exit(3) sends /3.
This catches missed runs and failures. It can't catch a script that hangs, and it can't say why it failed. The next section does both.
A small heartbeat helper
Save this next to your script as heartbeat.py. It uses only the standard library:
# heartbeat.py: start, finish and failure pings for a Python script.
import json, os, sys, time, uuid, urllib.request
from contextlib import contextmanager
PING = os.environ.get("STALLBELL_PING_URL", "https://stallbell.com/p/TOKEN")
def ping(path, **fields):
body = json.dumps(fields).encode()
req = urllib.request.Request(PING + path, data=body, method="POST",
headers={"content-type": "application/json"})
try:
urllib.request.urlopen(req, timeout=10).read()
except Exception as exc: # monitoring must never break the job
print("heartbeat ping failed:", exc, file=sys.stderr)
@contextmanager
def heartbeat():
run_id = str(uuid.uuid4())
started = time.monotonic()
extra = {} # anything set here goes out with the success ping
ping("/start", run_id=run_id)
try:
yield extra
except SystemExit as exc:
code = exc.code if isinstance(exc.code, int) else (0 if exc.code is None else 1)
ping(f"/{min(max(code, 0), 255)}", run_id=run_id,
duration_ms=int((time.monotonic() - started) * 1000))
raise
except BaseException as exc:
ping("/fail", run_id=run_id, msg=f"{type(exc).__name__}: {exc}"[:500],
duration_ms=int((time.monotonic() - started) * 1000))
raise
else:
ping("/0", run_id=run_id, duration_ms=int((time.monotonic() - started) * 1000), **extra)Then wrap the work:
# report.py
from heartbeat import heartbeat
def main():
... # your job
if __name__ == "__main__":
with heartbeat():
main()What each part does:
| Part | Why |
|---|---|
/start with a run_id | Opens a run, so Stallbell can alert if the script starts and never finishes |
/0 | Reports success. Stallbell joins it to the start by run_id |
/fail with msg | Reports a failure with the exception's type and message. Stallbell keeps up to 500 characters and shows it on the alert |
SystemExit | sys.exit(n) reports /n, so exit codes still mean what they mean in your shell |
timeout=10 | urlopen takes a timeout in seconds, so a slow network can't hold the script up for long |
except Exception in ping | A failed ping prints a warning and the job carries on |
Put the ping URL in the STALLBELL_PING_URL environment variable rather than in the code. Anyone who has the URL can check in for that monitor. You can rotate it from the monitor page.
Set up the monitor
- Sign in to Stallbell. Open the monitor (Monitors in the top bar) and set its schedule to match how the script runs: a period in Every, or How it runs set to On a cron schedule with the same cron expression and Schedule timezone. Press Save alert settings.
- Set Stuck after a little above the script's slowest normal run. The default is 1 hour.
- Copy the ping URL,
https://stallbell.com/p/TOKEN, intoSTALLBELL_PING_URL.
Stallbell starts watching for missed runs after the first check-in, so run the script once by hand.
What you'll hear about
- The script didn't run (the scheduler stopped, the server was off): no finish ping by the expected time plus the grace period, so you get a Missed run alert.
- It raised or exited non-zero: a fail ping, so you get a Failed run alert with the error.
- It hung: a start with no finish, so you get a Stuck run alert after Stuck after.
Alerts go by email, Slack or a signed webhook, and you get a message when the script recovers.
Optional: report what the script produced
If an empty result means something went wrong, send it with the finish ping. The monitor's Flag empty output setting, on by default, then alerts on a blank result. The helper sends whatever you put in the object it yields:
with heartbeat() as hb:
summary = build_summary()
hb["output"] = summary[:2000]Stallbell stores the first 2 KB of output and rejects any request body over 16 KB, so trim it first.
Test it
- Check the URL from a terminal. It should return
{"ok":true,...}:
bash curl -fsS -m 10 "https://stallbell.com/p/TOKEN/0"
- Run the script once. Recent runs on the monitor page should show an
OKrun with its duration. - Add
raise RuntimeError("test failure")tomain()and run it again. You should get a Failed run alert that saysRuntimeError: test failure. Remove the line afterwards.
FAQ
Do I need the requests library? No. urllib.request is in the standard library. If you already use requests, the same three POSTs work with it.
What if Stallbell is unreachable? The ping prints a warning to stderr and the script carries on. Stallbell would then see a missed run instead.
Does this work for a long-running worker rather than a scheduled script? Yes. Call ping("/0") every few minutes from the worker and give the monitor the same fixed interval. If the pings stop, you get a missed-run alert.
What does it cost? There's a Free plan with no card. Plans and limits are on the pricing page.
Related: What is heartbeat monitoring? · How to monitor cron jobs · Detect stuck jobs
Sources
Python behaviour on this page comes from Python's own docs, read on 9 November 2026:
- urllib.request (
urlopenand its timeout in seconds,Requestwithdataandmethod) - sys.exit (zero is successful termination, nonzero is abnormal)
Stallbell's side comes from the docs.