Skip to main content

Data and monitoring · Intermediate · 25 min

Alert when a cron job or batch job silently stops running

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Prometheus 3.16.0 · Pushgateway 1.11.4

You will have a nightly backup job that pushes its last-success time and duration to Pushgateway 1.11, and tested Prometheus 3.16 alert rules that fire when the job is late, slow or has never reported, plus a heartbeat ping as a second, independent check.

On this page

A backup that fails loudly gets fixed the same morning. A backup that quietly stops running gets found months later, on the day you need to restore. Cron does not tell anyone when a job is missing: if the crontab line was deleted, the server was rebuilt, the disk filled up or the script started failing before it reached the end, nothing happens, and silence looks exactly like success.

Prometheus normally pulls metrics from long-running programs. A cron job lives for a few seconds and is gone before the next scrape, so it pushes instead. The Pushgateway is a small server that keeps the last values each job pushed and lets Prometheus scrape them. The trick that turns this into an alarm is to push a timestamp, not a status: at the end of a successful run, the job records "I last succeeded at this second". Prometheus can then alert when time() minus that timestamp is larger than the schedule plus some slack. A job that never runs, crashes halfway or loses its crontab line all look the same: a timestamp that keeps getting older.

In this tutorial you install the Pushgateway on 127.0.0.1, connect it to the Prometheus and Alertmanager from the Alertmanager tutorial, wrap a small demo backup in a script that reports its success, schedule it with cron, and write four alert rules that you test with promtool before trusting them. At the end you add a heartbeat ping, a second check that does not depend on your own monitoring being up. The Pushgateway is installed from the official release file, so it gets no apt updates; the last step says how to upgrade or remove it.

Step 1 · Install the Pushgateway

Install the tools you need, including cron (Ubuntu Server usually has it already), and record the version and your CPU architecture. Keep working in this terminal, or set the variables again if you open a new one:

Bash
sudo apt update
sudo apt install -y curl jq tar cron
PG_VERSION=1.11.4
ARCH="$(dpkg --print-architecture)"
echo "$ARCH"

Check https://github.com/prometheus/pushgateway/releases for a newer version before you start. Download the release file and its checksum list into a work folder, check it, and install the program:

Bash
mkdir -p ~/jobwatch-install
cd ~/jobwatch-install
BASE="https://github.com/prometheus/pushgateway/releases/download/v${PG_VERSION}"
curl -fsSLO "${BASE}/pushgateway-${PG_VERSION}.linux-${ARCH}.tar.gz"
curl -fsSL -o pushgateway-sha256sums.txt "${BASE}/sha256sums.txt"
sha256sum --ignore-missing -c pushgateway-sha256sums.txt
tar -xzf "pushgateway-${PG_VERSION}.linux-${ARCH}.tar.gz"
sudo install -o root -g root -m 0755 "pushgateway-${PG_VERSION}.linux-${ARCH}/pushgateway" /usr/local/bin/pushgateway
sudo useradd --system --no-create-home --shell /usr/sbin/nologin pushgateway

The checksum line ends in OK. The pushgateway user has no password, home folder or shell; it exists only to run this program.

Check it worked

Bash
pushgateway --version 2>&1 | head -n 1

The output starts with pushgateway, version 1.11.4.

Step 2 · Run it as a service that survives restarts

Two flags matter here. --web.listen-address=127.0.0.1:9091 keeps it private: the Pushgateway has no login by default, and anyone who can reach it can overwrite or delete your job metrics. --persistence.file saves pushed values to disk. Without it, every restart of the Pushgateway wipes the last-success timestamps, and your alerts lose the very history they depend on:

Bash
sudo tee /etc/systemd/system/pushgateway.service > /dev/null <<'UNIT'
[Unit]
Description=Prometheus Pushgateway
After=network-online.target
Wants=network-online.target

[Service]
User=pushgateway
Group=pushgateway
StateDirectory=pushgateway
ExecStart=/usr/local/bin/pushgateway \
  --web.listen-address=127.0.0.1:9091 \
  --persistence.file=/var/lib/pushgateway/metrics.store
Restart=on-failure
NoNewPrivileges=true
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
UNIT

StateDirectory=pushgateway makes systemd create /var/lib/pushgateway, owned by the service user. Start it now and at every boot:

Bash
sudo systemctl daemon-reload
sudo systemctl enable --now pushgateway
sudo systemctl status pushgateway --no-pager

The status shows active (running).

Check it worked

Push one value by hand, read it back, then delete it. The URL path is the grouping key: job/hello/instance/manual means "the metrics of job hello on instance manual":

Bash
curl -fsS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9091/-/ready
echo 'hello_pushed_value 42' | curl -fsS --data-binary @- http://127.0.0.1:9091/metrics/job/hello/instance/manual
curl -s http://127.0.0.1:9091/metrics | grep '^hello_pushed_value'
curl -fsS -X DELETE http://127.0.0.1:9091/metrics/job/hello/instance/manual
ss -tln | grep 9091

You see 200, then hello_pushed_value{instance="manual",job="hello"} 42. After the delete the value is gone. The last line shows the Pushgateway listening on 127.0.0.1:9091 only.

Step 3 · Let Prometheus scrape the Pushgateway

Add a scrape job with honor_labels: true. Without it, Prometheus overwrites the job and instance labels your backup pushed with its own (job="pushgateway", instance="127.0.0.1:9091") and renames yours to exported_job and exported_instance, which makes every rule awkward to write.

The next command replaces the whole file with the one from the Alertmanager tutorial plus the new job, after keeping a copy. If your prometheus.yml has other jobs, such as the Blackbox ones, add only the pushgateway block to your file instead:

Bash
sudo cp /etc/prometheus/prometheus.yml /etc/prometheus/prometheus.yml.before-pushgateway
sudo tee /etc/prometheus/prometheus.yml > /dev/null <<'YAML'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  - /etc/prometheus/rules/*.yml

alerting:
  alertmanagers:
    - static_configs:
        - targets: ["127.0.0.1:9093"]

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["127.0.0.1:9090"]

  - job_name: node
    static_configs:
      - targets: ["127.0.0.1:9100"]

  - job_name: pushgateway
    honor_labels: true
    static_configs:
      - targets: ["127.0.0.1:9091"]
YAML
promtool check config /etc/prometheus/prometheus.yml

promtool prints SUCCESS. Reload Prometheus:

Bash
sudo systemctl reload prometheus

Check it worked

Wait for a scrape, then ask Prometheus whether it can reach the Pushgateway:

Bash
for i in $(seq 1 30); do
  v="$(curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=up{job="pushgateway"}' | jq -r '.data.result[0].value[1] // empty')"
  [ "$v" = 1 ] && break
  sleep 2
done
echo "up{job=\"pushgateway\"} = $v"

It prints up{job="pushgateway"} = 1. Note what this up measures: that the Pushgateway answers, not that any job ran. That is why the rules later look at the job's own timestamp.

Step 4 · Make the job report its last success

The demo job archives a folder into ~/jobwatch-demo/backups. Replace the tar line with your real backup later. The script pushes two gauges, and only after the work succeeded: set -euo pipefail stops the script at the first failing command, so a failed tar never reaches the push, and the timestamp stays at the previous good run:

Bash
mkdir -p ~/jobwatch-demo/data ~/jobwatch-demo/backups
echo 'invoice 1001, 25000 NGN' > ~/jobwatch-demo/data/ledger.txt
cat > ~/jobwatch-demo/backup.sh <<'SH'
#!/usr/bin/env bash
set -euo pipefail

PUSHGATEWAY="${PUSHGATEWAY:-http://127.0.0.1:9091}"
GROUP="$PUSHGATEWAY/metrics/job/backup/instance/$(hostname -s)"

start="$(date +%s)"
tar -czf "$HOME/jobwatch-demo/backups/data-$(date +%Y%m%d-%H%M%S).tar.gz" -C "$HOME/jobwatch-demo" data
end="$(date +%s)"

curl -fsS --max-time 10 --retry 3 --data-binary @- "$GROUP" <<EOF
# TYPE backup_last_success_timestamp_seconds gauge
backup_last_success_timestamp_seconds $end
# TYPE backup_duration_seconds gauge
backup_duration_seconds $((end - start))
EOF
echo "backup finished in $((end - start))s"
SH
chmod +x ~/jobwatch-demo/backup.sh

Some choices in it:

  • The grouping key is job/backup/instance/<short hostname>. Each server gets its own group. If two servers pushed to the same group, each push would replace the other's values, and one silent server would hide behind the other's success.
  • curl with --data-binary sends a POST, which replaces only the metric names in this push and leaves other metrics in the group alone. A PUT would replace the whole group.
  • The Pushgateway also adds push_time_seconds to every group. It changes on any push, including one a broken script sends on its way out, so an explicit success timestamp is the safer signal.
  • --retry 3 helps on a flaky link. If the server sits behind an unreliable connection or loses power often, as plenty of on-premises machines do, give the alert more slack rather than paging for every missed push.

Run it once the way cron will: with an almost empty environment and a short PATH. Many jobs that work in your shell fail under cron because of this:

Bash
env -i HOME="$HOME" PATH=/usr/bin:/bin SHELL=/bin/sh "$HOME/jobwatch-demo/backup.sh"

It prints backup finished in 0s (or a few seconds) and a new .tar.gz file appears in ~/jobwatch-demo/backups.

Check it worked

Read the values from the Pushgateway, then ask Prometheus how old the last success is, in seconds:

Bash
curl -s http://127.0.0.1:9091/metrics | grep '^backup_'
for i in $(seq 1 30); do
  age="$(curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=time() - backup_last_success_timestamp_seconds{job="backup"}' | jq -r '.data.result[0].value[1] // empty')"
  [ -n "$age" ] && break
  sleep 2
done
echo "last successful backup was ${age}s ago"
curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=backup_last_success_timestamp_seconds' | jq -c '.data.result[].metric'

The Pushgateway shows two backup_ lines with instance="<your hostname>" and job="backup". Prometheus reports an age of a few seconds, and the label set is {"__name__":"backup_last_success_timestamp_seconds","instance":"<your hostname>","job":"backup"}, with no exported_job. If you see exported_job, honor_labels: true is missing.

Step 5 · Schedule it with cron

Add one line to your crontab that runs the backup at 02:17 every night and keeps its output in a log. The command keeps any lines already in your crontab and appends this one. $HOME is expanded now, so the line holds your full path:

Bash
( crontab -l 2>/dev/null || true; echo "17 2 * * * $HOME/jobwatch-demo/backup.sh >> $HOME/jobwatch-demo/backup.log 2>&1" ) | crontab -

An odd minute such as 17 avoids the rush of jobs that every server starts at exactly 02:00. The cron tutorial covers the syntax and where cron logs its runs.

Check it worked

Bash
crontab -l | grep jobwatch-demo

You see your line, with /home/<you>/jobwatch-demo/backup.sh. From now on, the alert rules, not you, notice if that line disappears or the job stops finishing.

Step 6 · Write the alert rules and test them

Pick thresholds from the schedule. The job runs every 24 hours and normally takes minutes, so 26 hours without a success means at least one run is missing, with two hours of slack for a slow night or a late push. Four rules cover the ways a job goes quiet:

Bash
sudo tee /etc/prometheus/rules/jobs.yml > /dev/null <<'YAML'
groups:
  - name: scheduled-jobs
    rules:
      - alert: BackupTooOld
        expr: time() - backup_last_success_timestamp_seconds{job="backup"} > 26 * 3600
        for: 10m
        labels:
          severity: critical
        annotations:
          summary: "No successful backup on {{ $labels.instance }} for over 26 hours"

      - alert: BackupMetricMissing
        expr: absent(backup_last_success_timestamp_seconds{job="backup"})
        for: 30m
        labels:
          severity: critical
        annotations:
          summary: "No backup has reported to Prometheus at all"

      - alert: BackupTooSlow
        expr: backup_duration_seconds{job="backup"} > 3600
        labels:
          severity: warning
        annotations:
          summary: "Last backup on {{ $labels.instance }} took over an hour"

      - alert: PushgatewayDown
        expr: up{job="pushgateway"} == 0
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Prometheus cannot scrape the Pushgateway, so job alerts are blind"
YAML
promtool check rules /etc/prometheus/rules/jobs.yml

promtool prints SUCCESS: 4 rules found. What each one catches:

  • BackupTooOld is the main alarm: the job ran once and then stopped succeeding. Because the Pushgateway keeps the last value forever, the old timestamp stays visible and keeps ageing.
  • BackupMetricMissing catches the case where there is no timestamp at all: the job was never set up on a new server, or the Pushgateway lost its data. absent() returns a result only when no matching series exists. It cannot tell you which server is missing, which is why the per-instance rule above does most of the work.
  • BackupTooSlow warns early, before a slow job turns into a late one.
  • PushgatewayDown matters because when Prometheus cannot scrape the Pushgateway, the backup series go stale and the other rules see nothing.

time() is the Prometheus server's clock, and the timestamp comes from the job's server, so keep both clocks in sync. Ubuntu does this by default (with chrony on 26.04); timedatectl shows System clock synchronized: yes when it is working.

Now prove the rules do what you think. In this test, server db1 backs up at hour 0 and again at hour 24. Server db2 backs up at hour 0 and then never again, and its backups take over an hour. A second test has no backup metric at all:

Bash
cat > ~/jobwatch-demo/jobs-test.yml <<'YAML'
rule_files:
  - /etc/prometheus/rules/jobs.yml

evaluation_interval: 1m

tests:
  - interval: 1m
    input_series:
      - series: 'backup_last_success_timestamp_seconds{job="backup", instance="db1"}'
        values: '0x1439 86400x400'
      - series: 'backup_last_success_timestamp_seconds{job="backup", instance="db2"}'
        values: '0x1840'
      - series: 'backup_duration_seconds{job="backup", instance="db1"}'
        values: '120x1840'
      - series: 'backup_duration_seconds{job="backup", instance="db2"}'
        values: '4000x1840'
    alert_rule_test:
      - eval_time: 25h
        alertname: BackupTooOld
        exp_alerts: []
      - eval_time: 26h30m
        alertname: BackupTooOld
        exp_alerts:
          - exp_labels:
              severity: critical
              job: backup
              instance: db2
            exp_annotations:
              summary: "No successful backup on db2 for over 26 hours"
      - eval_time: 26h30m
        alertname: BackupMetricMissing
        exp_alerts: []
      - eval_time: 25h
        alertname: BackupTooSlow
        exp_alerts:
          - exp_labels:
              severity: warning
              job: backup
              instance: db2
            exp_annotations:
              summary: "Last backup on db2 took over an hour"

  - interval: 1m
    input_series:
      - series: 'up{job="pushgateway", instance="127.0.0.1:9091"}'
        values: '1x60'
    alert_rule_test:
      - eval_time: 20m
        alertname: BackupMetricMissing
        exp_alerts: []
      - eval_time: 45m
        alertname: BackupMetricMissing
        exp_alerts:
          - exp_labels:
              severity: critical
              job: backup
            exp_annotations:
              summary: "No backup has reported to Prometheus at all"
YAML
promtool test rules ~/jobwatch-demo/jobs-test.yml

In the input series, 0x1439 means the value 0 repeated for 1,440 one-minute samples (24 hours), and the value is the Unix time of the last success, with the test's clock starting at 0. At hour 25, db2's last success is 25 hours old: late, but within the slack, so nothing fires. Just after hour 26 it crosses the threshold, and ten minutes later the alert fires for db2 only. absent() copies the job="backup" label from the selector, which is why the second test expects it.

Reload Prometheus so it loads the new rule file:

Bash
sudo systemctl reload prometheus

Check it worked

promtool test rules prints SUCCESS. If you change a threshold and forget the test, it fails and prints the alerts it expected next to the ones it got. Prometheus also lists the group:

Bash
curl -s http://127.0.0.1:9090/api/v1/rules | jq -r '.data.groups[] | select(.name == "scheduled-jobs") | .rules[] | "\(.name) \(.state)"'

You see the four rules with state inactive, because the backup you ran a moment ago is fresh. If they show unknown, Prometheus has not evaluated the new group yet; wait 15 seconds and run the command again.

Step 7 · Watch a stale job trip the alert, then clean up after it

You can see the live rule react without waiting 26 hours. Push a success timestamp from 100,000 seconds ago (about 28 hours) for a made-up server called old-demo. The # TYPE line must match the one the backup script sends, or the Pushgateway rejects the push with 400:

Bash
printf '# TYPE backup_last_success_timestamp_seconds gauge\nbackup_last_success_timestamp_seconds %s\n' "$(( $(date +%s) - 100000 ))" | curl -fsS --data-binary @- http://127.0.0.1:9091/metrics/job/backup/instance/old-demo
for i in $(seq 1 30); do
  state="$(curl -s http://127.0.0.1:9090/api/v1/alerts | jq -r '.data.alerts[] | select(.labels.alertname == "BackupTooOld" and .labels.instance == "old-demo") | .state')"
  [ -n "$state" ] && break
  sleep 3
done
echo "BackupTooOld for old-demo: $state"

Within about 30 seconds it prints BackupTooOld for old-demo: pending. After ten minutes in that state it would turn firing and go to Alertmanager.

This is also the Pushgateway's biggest trap. It never forgets a group, so when you retire a server or rename a job, its last timestamp stays there and keeps ageing, and BackupTooOld fires for a machine that no longer exists. Delete the group when you retire something:

Bash
curl -fsS -X DELETE http://127.0.0.1:9091/metrics/job/backup/instance/old-demo

Check it worked

List the groups the Pushgateway holds:

Bash
curl -s http://127.0.0.1:9091/api/v1/metrics | jq -c '.data[].labels'

Only {"instance":"<your hostname>","job":"backup"} remains. Run this list now and then: any group you do not recognise is a job that someone retired without cleaning up. Prometheus drops the old-demo series at its next scrape, and the pending alert goes away.

Other limits worth knowing before you push everything through it:

  • One Pushgateway is a single point of failure for every job that reports to it. The PushgatewayDown rule tells you, but jobs that run while it is down lose their push.
  • Use it for jobs that start and finish. A long-running service should expose its own metrics for Prometheus to scrape, so that up tells you when it dies.
  • To accept pushes from other servers, change the listen address to a private one, allow port 9091 from those servers only in the firewall, and set a password and TLS with --web.config.file.

Step 8 · Add a heartbeat as a second, independent check

Everything so far runs on your own monitoring. If the Prometheus server is down, or Alertmanager cannot send mail, the backup can stop and nobody hears. A heartbeat service (sometimes called a dead man's switch) works the other way round: the job calls a unique URL at the end of each run, and the service, running somewhere else, alerts you when the call does not arrive on time. Healthchecks.io is one such service; its code is open source, so you can also host it yourself. Many uptime services offer the same feature.

The two approaches complement each other:

  • The Pushgateway gives you history, duration and per-server labels inside Prometheus, and alerts through the routing you already have.
  • A heartbeat keeps working when your monitoring is down, and needs no server of yours. It knows only "pinged on time or not", and the ping URL is a credential: anyone who has it can report success, so keep it out of scripts and Git.

Create your check in the service, with a period of one day and a grace time of about two hours, matching the alert rule. Then store its ping URL in a private file. The file is created with mode 600 before anything goes in:

Bash
mkdir -p ~/.config/jobwatch
install -m 600 /dev/null ~/.config/jobwatch/heartbeat-url

Open it and paste the ping URL from your heartbeat service on the first line, such as https://hc-ping.com/<your-check-id>:

Bash
nano ~/.config/jobwatch/heartbeat-url

Now rewrite the script so it pings on success, and pings the URL with /fail added when any command fails. Healthchecks.io, and some other heartbeat services, treat /fail as an immediate failure instead of waiting for the grace time to run out; check how yours signals one. A failed ping never fails the backup itself:

Bash
cat > ~/jobwatch-demo/backup.sh <<'SH'
#!/usr/bin/env bash
set -euo pipefail

PUSHGATEWAY="${PUSHGATEWAY:-http://127.0.0.1:9091}"
GROUP="$PUSHGATEWAY/metrics/job/backup/instance/$(hostname -s)"
HEARTBEAT_FILE="$HOME/.config/jobwatch/heartbeat-url"
HEARTBEAT_URL=""
if [ -r "$HEARTBEAT_FILE" ]; then
  HEARTBEAT_URL="$(head -n 1 "$HEARTBEAT_FILE")"
fi

ping_heartbeat() {
  if [ -n "$HEARTBEAT_URL" ]; then
    curl -fsS --max-time 10 --retry 3 -o /dev/null "${HEARTBEAT_URL}$1" || echo "heartbeat ping failed" >&2
  fi
}
trap 'ping_heartbeat /fail' ERR

start="$(date +%s)"
tar -czf "$HOME/jobwatch-demo/backups/data-$(date +%Y%m%d-%H%M%S).tar.gz" -C "$HOME/jobwatch-demo" data
end="$(date +%s)"

curl -fsS --max-time 10 --retry 3 --data-binary @- "$GROUP" <<EOF
# TYPE backup_last_success_timestamp_seconds gauge
backup_last_success_timestamp_seconds $end
# TYPE backup_duration_seconds gauge
backup_duration_seconds $((end - start))
EOF
ping_heartbeat ""
echo "backup finished in $((end - start))s"
SH
chmod +x ~/jobwatch-demo/backup.sh

Check it worked

Run the job once normally, then once with its data folder moved away so tar fails. With a real heartbeat service, the failed run sends you a failure notice, so warn your team first or skip that half:

Bash
env -i HOME="$HOME" PATH=/usr/bin:/bin SHELL=/bin/sh "$HOME/jobwatch-demo/backup.sh"
mv ~/jobwatch-demo/data ~/jobwatch-demo/data.away
if env -i HOME="$HOME" PATH=/usr/bin:/bin SHELL=/bin/sh "$HOME/jobwatch-demo/backup.sh"; then
  echo "unexpected success"
  false
else
  echo "backup failed as expected"
fi
mv ~/jobwatch-demo/data.away ~/jobwatch-demo/data

The first run prints backup finished in 0s. The second prints a tar error and backup failed as expected. In your heartbeat service's log for the check, you see a success ping followed by a failure ping. In Prometheus, the last-success timestamp still shows the first run, because the failed run never reached the push.

Step 9 · Upgrade or remove the Pushgateway

The Pushgateway gets no updates from apt. Watch the release page and, to upgrade, repeat the download, checksum and tar commands from the first step in ~/jobwatch-install with the new PG_VERSION, then, still in that folder, swap the program while the service is stopped. The persistence file keeps your timestamps across the restart:

Bash
sudo systemctl stop pushgateway
sudo install -o root -g root -m 0755 "pushgateway-${PG_VERSION}.linux-${ARCH}/pushgateway" /usr/local/bin/pushgateway
sudo systemctl start pushgateway

To check an upgrade, run pushgateway --version: it prints the new version number. curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9091/-/ready still prints 200.

If this was a trial, remove what you created. This deletes the stored job metrics and the demo backups, and puts back the Prometheus configuration you saved before this tutorial, so check that you no longer need them. The crontab command removes only the line that mentions jobwatch-demo/backup.sh and keeps the rest:

Bash
( crontab -l | grep -v 'jobwatch-demo/backup.sh' || true ) | crontab -
sudo systemctl disable --now pushgateway
sudo rm /etc/systemd/system/pushgateway.service
sudo systemctl daemon-reload
sudo rm /usr/local/bin/pushgateway
sudo rm -r /var/lib/pushgateway
sudo userdel pushgateway
sudo rm /etc/prometheus/rules/jobs.yml
sudo mv /etc/prometheus/prometheus.yml.before-pushgateway /etc/prometheus/prometheus.yml
sudo systemctl reload prometheus
rm -rf ~/jobwatch-demo ~/jobwatch-install ~/.config/jobwatch

Delete the check in your heartbeat service too, or it alerts you the next night.

Check it worked

Bash
command -v pushgateway || echo "pushgateway removed"
crontab -l 2>/dev/null | grep -c jobwatch-demo || true

It prints pushgateway removed and 0.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.