Know when a Raspberry Pi script stops running after a reboot or power cut

Updated 4 min read

On this page
  1. The problem
  2. What goes wrong silently
  3. Setup
  4. Recommended settings
  5. Pi cron gotchas
  6. Related
  7. FAQ

Your Pi pings Stallbell every time the script runs, and Stallbell emails you if the script fails or the pings stop.

The problem

A Pi in a cupboard runs a script every 15 minutes: a sensor log, a backup, a home-automation check. Then there's a power cut, the SD card fills up, the Wi-Fi doesn't come back, or a package update moves python3 into a virtualenv cron can't see. The script stops, and the Pi gives no sign of it. You notice weeks later when the graph has a hole in it.

This page is a ready-made setup for one scenario.

What goes wrong silently

What Stallbell catches
What happensWhat Stallbell seesAlert
The script exits with an error (a sensor read fails, a file can't be written)The exit code in the pingFailed run
A command isn't on cron's PATHExit code 127Failed run
A power cut, a dead SD card or lost Wi-FiNo ping by the expected time plus graceMissed run
The crontab line was lost in a reinstallNo pingMissed run
The Pi comes back and the script runsA good ping after the incidentRecovered

Creates a monitor called raspberry-pi-heartbeat with the settings below. You can change everything later.

Setup

Run crontab -e on the Pi and put the ping straight after your script, on the same line:

crontab
*/15 * * * * /usr/bin/python3 /home/pi/read_sensor.py; curl -fsS -m 10 --retry 3 https://stallbell.com/p/TOKEN/$? > /dev/null
Python
# Or report from inside the script (standard library only).
import os
import sys
import urllib.request

PING = "https://stallbell.com/p/TOKEN"

def ping(path=""):
    try:
        urllib.request.urlopen(PING + path, timeout=10).read()
    except Exception as exc:  # never let monitoring break the job
        print(f"Stallbell ping failed: {exc}", file=sys.stderr)

def read_sensor():
    ...  # your job: return a reading

try:
    value = read_sensor()
    with open(os.path.expanduser("~/readings.log"), "a") as f:
        f.write(f"{value}\n")
except Exception:
    ping("/fail")
    raise
ping()

In the crontab version, $? is your script's exit code, so /0 reports a good run and any other number a failure. The ; makes sure curl runs either way. In the Python version, a bare ping is a good run, and an exception sends /fail before the traceback, so the exit code is still non-zero.

Once it has run, Recent runs on the monitor page shows the run and its status. Click it to see the exit code in the Run drawer.

Recommended settings
FieldValueWhy
KindScheduled jobA label only. The script runs from the Pi's crontab.
How it runsOn a fixed intervalThe crontab line runs every 15 minutes, so a fixed interval matches it.
Every15 minutes15 minutes, the same as the */15 crontab line.
Grace period10 minutes10 minutes leaves room for Wi-Fi to reconnect after a reboot.
Failures in a row1A home-lab script that exits non-zero has usually stopped for good, so the first failure alerts.
Stuck after10 minutesNot used by the one-liner, which pings only at the end. 10 minutes keeps it tight if you add a start ping.

Pi cron gotchas

Cron has a short PATH. Debian's cron, which Raspberry Pi OS uses, starts jobs with PATH=/usr/bin:/bin. A command that works in your shell, such as a virtualenv's python or anything in /usr/local/bin, fails under cron with exit code 127. With the ping on the line, that shows up as a Failed run instead of silence. Use full paths, for example /home/pi/sensor/.venv/bin/python.

@reboot runs before the network is up. A job that pings at boot can fire before Wi-Fi connects, and the ping is lost. Add a delay: @reboot sleep 60; /usr/bin/python3 /home/pi/startup.py; curl …/$?. Keep the */15 heartbeat as well, since a job that only runs at boot has no next run to miss.

--retry doesn't retry everything. curl's --retry covers timeouts and some HTTP errors. In our test it gave up at once on a refused connection. On flaky Wi-Fi, add --retry-all-errors so a brief outage doesn't lose the ping. The next run would catch up anyway: the 10-minute grace period is there for that.

Keep $? straight after the script. read_sensor.py; echo done; curl …/$? reports the exit code of echo (0), not of your script.

FAQ

My script works when I run it, but not from cron. Why?

Usually PATH. Debian's cron, which Raspberry Pi OS uses, starts jobs with PATH=/usr/bin:/bin, so a command from a virtualenv or /usr/local/bin isn't found and the job exits 127. Use full paths in the crontab line.

Can Stallbell tell me why the Pi went quiet?

No. A power cut, a full SD card and lost Wi-Fi all look the same from outside: no ping. Stallbell tells you it stopped, and when.

Does it work for @reboot jobs?

Partly. The exit code ping works at boot, but a job that runs only at boot has no next run, so there is nothing to miss. Keep a scheduled heartbeat as well, and add a sleep so the network is up before the ping.

Is this free?

The Free plan has 10 monitors and alerts by email, Slack and webhook. Its shortest fixed interval is 15 minutes, so a 15-minute heartbeat fits.