# Cron job failure notification on your phone · Ahem

Source: https://useahem.com/guides/cron-job-failure-notification

1.  [Home](https://useahem.com)
2.  [Guides](https://useahem.com/guides)
3.  Cron job failure notification

# Get a notification when a cron job fails

By [Bohdan Stefaniuk](https://useahem.com/about) · Updated 2 December 2026 · 9 min read

Tested 2 December 2026 with cron and systemd 252 on Debian 12, and sh on macOS 26, sending to the live Ahem API.

To get a notification when a cron job fails, run the job through a small wrapper script. It notes the exit code, how long the job took and the last 20 lines of output, and when the exit code isn’t 0 it sends an error alert to Ahem, an event inbox for developers. Your phone shows “nightly-backup failed on web-1 (exit 1)” with the log lines underneath. Cron on its own only emails a job’s output, which most servers can’t send. A wrapper can’t report a job that never started; for that you need a heartbeat check, covered below.

## What you need

-   A Linux or macOS machine whose jobs run from cron or a systemd timer, with `curl` (nothing else: no `jq`, no Python).
-   An Ahem account (the free plan is enough), a project for your servers, and an API key for it.
-   The Ahem app on your phone, or browser notifications turned on.

## Set up a cron job failure notification, step by step

1.  **Create a project and a key.** In Ahem, create a project, for example “Servers”, and an API key for it. Note the project’s address: addresses are unique across Ahem, so yours may be `servers-48213` rather than `servers`. The app shows it in the example request next to the key.
    
2.  **Save the wrapper** as `run-and-report.sh` and install it:
    
    ```sh
    #!/bin/sh
    # run-and-report: runs a command, and tells Ahem when it fails.
    # Usage: run-and-report NAME COMMAND [ARGUMENTS...]
    #   AHEM_KEY         an API key of your project
    #   AHEM_PROJECT     the project's address, as the app shows it
    #   AHEM_CHANNEL     the channel, "cron" if not set
    #   AHEM_ON_SUCCESS  set to 1 to also record successful runs (sent silent, so they never buzz)
    # The job's exit code is this script's exit code, and its output (standard error merged into
    # standard output) is printed when the job ends, so cron mail and log files still get it.
    [ $# -ge 2 ] || { echo "usage: run-and-report NAME COMMAND [ARGUMENTS...]" >&2; exit 64; }
    name=$1; shift
    log=$(mktemp) || exec "$@"   # no temporary file: run the job anyway, unreported
    trap 'rm -f "$log"' EXIT
    trap 'exit 143' TERM; trap 'exit 130' INT; trap 'exit 129' HUP   # so the EXIT trap cleans up when killed
    
    start=$(date +%s)
    "$@" >"$log" 2>&1
    code=$?
    duration=$(($(date +%s) - start))
    cat "$log"
    
    [ "$code" -ne 0 ] || [ "${AHEM_ON_SUCCESS:-0}" = 1 ] || exit 0
    if [ -z "$AHEM_PROJECT" ] || [ -z "$AHEM_KEY" ]; then
      echo "run-and-report: set AHEM_KEY and AHEM_PROJECT to report to Ahem" >&2; exit "$code"
    fi
    
    # A JSON string: control characters dropped (tabs kept), \ and " escaped, lines joined with \n.
    json() {
      # Invalid UTF-8 would make Ahem refuse the event, so iconv drops it. Without iconv, cat passes the text on.
      { iconv -c -f UTF-8 -t UTF-8 2>/dev/null || cat; } | tr -d '\000-\010\013-\037' |
        awk 'BEGIN { ORS = "" } { gsub(/\\/, "&&"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR > 1) print "\\n"; print }'
    }
    host=$(uname -n)
    if [ "$code" -eq 0 ]; then
      title="$name succeeded on $host"; level=success; type=cron.succeeded; notify=silent
      body="Took ${duration}s."
    else
      title="$name failed on $host (exit $code)"; level=error; type=cron.failed; notify=default
      body=$(printf 'Exit code %s after %ss. The last lines of output:\n\n~~~\n%s\n~~~' \
        "$code" "$duration" "$(tail -n 20 "$log" | LC_ALL=C cut -c 1-400)")
    fi
    
    # The key goes in a file only you can read, not on curl's command line, where ps would show it.
    headers=$(mktemp) || exit "$code"
    trap 'rm -f "$log" "$headers"' EXIT
    printf 'Authorization: Bearer %s\n' "$AHEM_KEY" >"$headers"
    response=$(printf '{"title":"%s","body":"%s","level":"%s","type":"%s","notify":"%s","group":"%s",
    "metadata":{"job":"%s","host":"%s","exit_code":%s,"duration_s":%s}}' \
      "$(printf '%s' "$title" | json)" "$(printf '%s' "$body" | json)" "$level" "$type" "$notify" \
      "$(printf '%s' "$name" | json)" "$(printf '%s' "$name" | json)" "$(printf '%s' "$host" | json)" \
      "$code" "$duration" |
      curl -sS -m 10 --retry 3 --retry-connrefused "https://api.useahem.com/v1/channels/$AHEM_PROJECT/${AHEM_CHANNEL:-cron}" \
        -H @"$headers" -H "Content-Type: application/json" \
        -H "Idempotency-Key: $host-$name-$start-$$" --data-binary @- -w '\n%{http_code}' 2>&1)
    case $(printf '%s' "$response" | tail -n 1) in
      2??) ;;
      *) printf 'run-and-report: Ahem did not take the event: %s\n' "$response" >&2 ;;
    esac
    exit "$code"
    ```
    
    ```sh
    sudo install -m 755 run-and-report.sh /usr/local/bin/run-and-report
    ```
    
    It runs the job with its output (standard error included) going to a temporary file, then prints that output, so your log files and cron mail still get it. The key goes to `curl` in a file, so it doesn’t show in `ps`. The JSON is escaped with `awk` and invalid UTF-8 is dropped with `iconv`, so quotes, backslashes, colour codes or binary junk in the output can’t get the event refused. Each job name is the event’s `group`, so all runs of one job are one thread in the inbox. Every field it sends is in the [API reference](https://app.useahem.com/docs/events).
    
3.  **Put it in front of the job** in your crontab (`crontab -e`), with the key and the address at the top. Cron doesn’t read your shell profile, so they have to be here. The log goes to your home folder: in a normal user’s crontab, a log file the user can’t write to (such as one in `/var/log`) stops the job from starting at all.
    
    ```sh
    AHEM_KEY=ak_live_…
    AHEM_PROJECT=servers-48213
    
    # m h dom mon dow  command
    0 3 * * * /usr/local/bin/run-and-report nightly-backup /usr/local/bin/backup.sh >> "$HOME/backup.log" 2>&1
    ```
    
4.  **Try a failure** by hand. Your phone shows “test-job failed on … (exit 1)” and the wrapper exits 1, like the command:
    
    ```sh
    AHEM_KEY=ak_live_… AHEM_PROJECT=servers-48213 \
      run-and-report test-job sh -c 'echo "something broke" >&2; exit 1'
    ```
    

For example, a backup that couldn’t reach its database sends this event:

```json
{
  "title": "nightly-backup failed on web-1 (exit 1)",
  "body": "Exit code 1 after 2s. The last lines of output:\n\n~~~\ndumping database shop\npg_dump: error: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: No such file or directory\n~~~",
  "level": "error",
  "type": "cron.failed",
  "notify": "default",
  "group": "nightly-backup",
  "metadata": { "job": "nightly-backup", "host": "web-1", "exit_code": 1, "duration_s": 2 }
}
```

## With a systemd timer

If the job is a systemd service started by a timer, let systemd report it. `OnFailure=` starts another unit when the service fails, and that also covers what a wrapper can’t see from inside: a `TimeoutStartSec` timeout, a crash or the out-of-memory killer. The result is in the title (`exit-code`, `timeout`, `signal`, `oom-kill`), and the last 20 lines come from this run’s journal only.

The job and its timer, with one extra line, `OnFailure=`:

```ini
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
OnFailure=ahem-failed@%n.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
```

```ini
# /etc/systemd/system/backup.timer
[Unit]
Description=Run the backup every night at 03:00

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target
```

One template unit that any service can name in its `OnFailure=`, and the key in a file only root can read:

```ini
# /etc/systemd/system/ahem-failed@.service
[Unit]
Description=Tell Ahem that %i failed

[Service]
Type=oneshot
EnvironmentFile=/etc/ahem.env
ExecStart=/usr/local/bin/ahem-failed %i
```

```sh
# /etc/ahem.env (sudo chmod 600 /etc/ahem.env)
AHEM_KEY=ak_live_…
AHEM_PROJECT=servers-48213
```

The script it runs, saved as `ahem-failed.sh`:

```sh
#!/bin/sh
# ahem-failed: tells Ahem that a systemd unit failed. Started by ahem-failed@.service, which
# systemd runs through OnFailure= with the failed unit's name as the argument.
unit=$1
show() { systemctl show -p "$1" --value "$unit"; }
result=$(show Result)        # exit-code, timeout, signal, oom-kill, …
code=$(show ExecMainStatus)
lines=$(journalctl _SYSTEMD_INVOCATION_ID="$(show InvocationID)" -n 20 -o cat --no-pager | LC_ALL=C cut -c 1-400)
host=$(uname -n)

json() {
  # Invalid UTF-8 would make Ahem refuse the event, so iconv drops it. Without iconv, cat passes the text on.
  { iconv -c -f UTF-8 -t UTF-8 2>/dev/null || cat; } | tr -d '\000-\010\013-\037' |
    awk 'BEGIN { ORS = "" } { gsub(/\\/, "&&"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR > 1) print "\\n"; print }'
}
headers=$(mktemp) || exit 1   # the key goes in a file, not on curl's command line where ps shows it
trap 'rm -f "$headers"' EXIT
printf 'Authorization: Bearer %s\n' "$AHEM_KEY" >"$headers"
body=$(printf 'Result: %s, exit status %s. The last lines of its log:\n\n~~~\n%s\n~~~' "$result" "$code" "$lines")

printf '{"title":"%s","body":"%s","level":"error","type":"cron.failed","group":"%s",
"metadata":{"unit":"%s","host":"%s","result":"%s","exit_code":%s}}' \
  "$(printf '%s failed on %s (%s)' "$unit" "$host" "$result" | json)" "$(printf '%s' "$body" | json)" \
  "$(printf '%s' "$unit" | json)" "$(printf '%s' "$unit" | json)" "$(printf '%s' "$host" | json)" "$result" "${code:-0}" |
  curl -sS -m 10 --retry 3 --retry-connrefused "https://api.useahem.com/v1/channels/$AHEM_PROJECT/${AHEM_CHANNEL:-cron}" \
    -H @"$headers" -H "Content-Type: application/json" \
    -H "Idempotency-Key: $host-$(show InvocationID)" --data-binary @-
```

Then install and start it:

```sh
sudo install -m 755 ahem-failed.sh /usr/local/bin/ahem-failed
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
sudo systemctl start backup.service    # run it once now, to see a failure arrive
```

To report another service, add `OnFailure=ahem-failed@%n.service` to its `[Unit]` section.

## Make it quieter

-   **Only failures buzz.** The wrapper sends nothing for a successful run unless you set `AHEM_ON_SUCCESS=1`; then successes are recorded as silent events, kept but never pushed. A job every five minutes makes about 8,640 events a month that way, more than the free plan’s 3,000, so keep it for the jobs whose history you want.
-   **A channel per kind of job.** Set `AHEM_CHANNEL` to send a noisy job somewhere else, then set that channel’s [notification rule](https://useahem.com/features/notification-rules) in the app: every event, warnings and errors, errors only, or off.
-   **Count failures.** A [counter](https://useahem.com/features/counters) of `cron.failed` for this week, on the project overview, tells you if a flaky job is getting worse.

## What a wrapper can’t catch: jobs that never run

The wrapper reports a job that ran and failed. It says nothing when the job never starts: the server is off, the crontab was overwritten, cron isn’t running, or the timer was disabled. Catching silence takes a heartbeat check, also called a dead man’s switch: the job pings a URL every time it succeeds, and a service alerts you when the ping doesn’t come. Free plans as their pricing pages listed them on 2 December 2026:

-   **[Healthchecks.io](https://healthchecks.io/pricing/)** is open source (BSD licence, self-hostable), and its free plan monitors 20 jobs.
-   **[Cronitor](https://cronitor.io/pricing)** has a free plan with 5 monitors.
-   **Ahem** silence alerts are planned (Planned). Until they ship, I’d use one of the two above for “didn’t run” and Ahem for “failed, and here’s the output”.

## Troubleshooting

-   **It works in a terminal but not from cron.** Cron runs with a short `PATH` (often `/usr/bin:/bin`) and without your shell profile. Use full paths, and set `AHEM_KEY` and `AHEM_PROJECT` in the crontab as above.
-   **A `%` in the crontab line cuts the command short.** Cron turns `%` into a new line. Write `\%`, for example `date +\%F`, or move the command into a script.
-   **The job fails but no event arrives.** Look at the job’s log: when Ahem refuses an event the wrapper prints `run-and-report: Ahem did not take the event:` and the reason, such as a `404` for a wrong project address or a `401` for a wrong key.
-   **The job fails but exits 0.** A shell script exits with its last command’s code, so an error halfway through goes unnoticed. Start the script with `set -e`; in bash, add `set -o pipefail` so a failure inside a pipe counts too.
-   **The job hangs and nothing arrives.** The wrapper waits for the job as long as it runs. Give it a limit with `timeout`: when the limit is reached the job is stopped and the exit code is 124.
    
    ```sh
    0 3 * * * /usr/local/bin/run-and-report nightly-backup timeout 2h /usr/local/bin/backup.sh >> "$HOME/backup.log" 2>&1
    ```
    
-   **systemd: nothing arrives.** `journalctl -u 'ahem-failed@*'` shows the script’s run and Ahem’s answer. Check that `/etc/ahem.env` exists, and run `systemctl daemon-reload` after editing a unit.

## Other ways to do it

-   **`MAILTO` in the crontab.** Free and built in: cron emails whatever a job prints. It needs a working mail setup on the server, and it mails every job that prints anything, not only failures. `chronic` from moreutils helps there: it prints a job’s output only when the job fails.
-   **A heartbeat service** (above). It covers jobs that never run, which a wrapper can’t.
-   **A push service with the same wrapper.** Point the `curl` at ntfy or Pushover. You get the ping; you don’t get one searchable history of every failure across servers. See [Ahem vs Pushover](https://useahem.com/vs/pushover).
-   **A Telegram bot.** Works, with one chat for everything. See [Ahem vs a Telegram bot](https://useahem.com/vs/telegram-bot).

What Ahem adds is the record: every failure from every server in one inbox, a thread per job, the output kept with it, and a rule per channel for what wakes you. The same API works from [any other script](https://useahem.com/guides/push-notification-from-script).

FAQ

## Questions

**Does the wrapper change how my job runs?**

Barely. It runs the same command with the same arguments and exits with its exit code. Two things differ: standard error is merged into standard output, and the output is printed when the job ends rather than line by line. When the job fails it adds one HTTPS request.

**What happens if Ahem is down when a job fails?**

The wrapper gives each try 10 seconds and retries up to three times after a timeout, a refused connection or a server error, with an idempotency key so a retry never makes a second event. If all of them fail, it prints why and still exits with the job’s exit code, so cron and systemd see the failure as before.

**Can I see successful runs too?**

Yes. Set `AHEM_ON_SUCCESS=1` and every run is recorded, successes as silent events that never buzz. Each job is one thread, so its history reads top to bottom.

**Does Ahem tell me when a job didn’t run at all?**

Not yet. Silence alerts (“tell me if this job didn’t report”) are planned. Until then, use Healthchecks.io or Cronitor for that part.

**Is it free?**

The free plan includes 3,000 events a month. With only failures reported, that is 3,000 failures.

## Find out at 3:01, not at 9:00.

Create a free project, put the wrapper in front of one job, and the next failure reaches your phone with its output.

[Start free](https://app.useahem.com/sign-in) · [Read the API docs](https://app.useahem.com/docs)
