Did the Task Stop Running? How to Detect Jobs That Disappear Without Errors

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Silence is a failure too

A scheduled task can run smoothly for months… and then, on any random day, simply stop executing. Maybe someone accidentally modified the crontab, changed a path, disabled a service, or the server rebooted and something failed to restart.

The problem is that cron is under no obligation to notify you when a task you were expecting simply doesn’t run. There is no failing process, no non-zero exit code, and in many cases, no log entry indicating anything went wrong. There is only silence.

In previous articles, we explored how to catch errors during scheduled task execution and how to verify that backups can actually be restored. At the end of the first article, we left an open question: what happens if cron never even triggers the script?

Now we are going to solve it: how do you know if a task stopped running when you don’t even have an error to detect?

The solution lies in flipping the monitoring logic. Instead of waiting for a task to alert on failure, we have it check in periodically when it succeeds. If that signal stops arriving, the monitoring system assumes something is wrong. This mechanism is known as a Dead Man’s Switch or heartbeat monitoring.

1. The problem with silent tasks

Imagine a task that generates a report every morning at 2:00 AM. For weeks, it runs flawlessly and drops its file into the target directory.

One day, someone edits the crontab and accidentally deletes that line. The application keeps working, the server responds, and no errors appear in the logs. The report simply stops being generated. Unless someone manually checks that the file exists, days can pass before anyone notices.

Several scenarios cause this behavior:

  • A cron entry was accidentally removed or edited.
  • The cron daemon stopped running.
  • The server was powered down during the scheduled window.
  • A script changed locations or lost executable permissions.
  • A dependency became unavailable before the process could launch.
  • A task was disabled during maintenance and nobody re-enabled it.

In all these cases, monitoring based solely on exit codes falls short. You cannot detect an execution error if an execution never took place.

2. Dead Man’s Switch: monitoring the absence of a signal

The concept is simple: an external service expects to receive a periodic signal from a task. Each signal confirms that the job reached the expected point in its run. If the signal does not arrive within the designated timeframe, the service triggers an alert.

For instance, if a task runs daily at 2:00 AM and you configure a 30-minute grace period, the service expects to receive its signal before 2:30 AM. If it arrives, it records that the task is healthy. If it does not, it alerts that something might have gone wrong.

The workflow looks like this:

  1. The scheduled task starts running.
  2. It performs the job it was designed to do.
  3. If it completes successfully, it sends a signal to the monitoring service.
  4. The service logs the ping and resets the timer.
  5. If the deadline expires without receiving another signal, it fires an alert.

The key difference is that the monitoring system does not need access to the server or its log files. It only needs to know that it was expecting a signal and that the signal never arrived.

This is why the monitoring service must live outside the monitored server. If you host the monitor on the same machine, a complete outage would bring down both the task and the mechanism meant to notify you.

3. Services for monitoring scheduled tasks

You do not need to build this entire infrastructure from scratch. Several services already implement this pattern, letting you register tasks via a unique URL:

  • Healthchecks.io: scheduled task monitoring via HTTP pings, complete with intervals, grace periods, and notifications. It is open source, meaning you can self-host it, and it allows you to define expected schedules using cron expressions and timezones.
  • Cronitor: monitors cron, background processes, and scheduled jobs, providing run metrics and execution durations.
  • Uptime Kuma: a self-hosted uptime tool that can monitor endpoints and other services. For this use case, you can use a Push monitor with an expected heartbeat interval.

The core concept is identical across all of them: each task gets a dedicated monitoring endpoint and sends an HTTP request upon completing its work. The service does not need to know the contents of the backup, report, or executed script. It only needs to receive the corresponding ping.

In this article, we will use a generic URL for demonstration purposes. Each provider has its own URL structure and configuration options, so adapt the endpoints according to your chosen service’s documentation.

4. Implementing a heartbeat with curl

Suppose you have a task that generates a PostgreSQL backup every night. You want the monitoring service to receive a signal only when the backup is generated successfully.

The service provides a unique ping URL:

https://monitor.example.com/ping/IDENTIFICADOR

You can use curl to send the signal:

curl -fsS --max-time 10 --retry 3 \
  "https://monitor.example.com/ping/IDENTIFICADOR"

The options used are:

  • -f: treats HTTP errors as failures.
  • -sS: suppresses unnecessary output while keeping error messages visible.
  • --max-time 10: caps the request timeout at ten seconds.
  • --retry 3: retries up to three times on transient errors, preventing a brief network hiccup from triggering a false alert.

Where you place this call matters. Do not send it at the start of the script, as that only proves the task began. It must execute only after the work has finished successfully.

This example reuses the log function from comun.sh, identical to previous articles:

#!/usr/bin/env bash
set -Eeuo pipefail

source /opt/scripts/comun.sh   # log()

# La URL identifica tu tarea: trátala como una credencial.
HEALTHCHECK_URL="${HEALTHCHECK_URL:?Define HEALTHCHECK_URL}"

DESTINO="/backups/mibase_$(date +%F).dump"
TEMP=$(mktemp "${DESTINO}.XXXXXX")

limpiar() {
    [ -z "${TEMP:-}" ] || rm -f -- "$TEMP"
}

trap limpiar EXIT

log INFO "Iniciando respaldo"

# Generar el dump en un archivo temporal.
pg_dump -Fc mibase > "$TEMP"

# Comprobar que pg_restore puede procesar su contenido.
pg_restore -f /dev/null "$TEMP"

# Publicar el archivo definitivo solo después de las comprobaciones.
mv -- "$TEMP" "$DESTINO"
TEMP=""

log OK "Respaldo generado y verificado estructuralmente"

curl -fsS --max-time 10 --retry 3 \
    "$HEALTHCHECK_URL" >/dev/null

log INFO "Heartbeat enviado"

Two critical decisions are made in this example:

  • The backup is generated into a temporary file. If pg_dump fails, an incomplete file is never published under the final name.
  • mv only publishes the backup after validating that pg_restore can read it. Since both paths are in the same directory, the rename operation is atomic.

If pg_dump fails, the script exits without sending the success signal. If the server cannot reach the monitoring service, the request also fails. In both cases, the monitor stops receiving the expected signal and raises an alert.

There is an important nuance here: this check ensures the dump was generated and can be read, but not that the data can be fully restored into a clean database. That validation belongs to the testing workflow covered in the previous article. Ideally, you should send the signal only after completing every check required to consider the backup genuinely valid.

A note on retries: if a network response is dropped, curl might retry a request that the server actually received. Heartbeat services are idempotent and handle duplicate pings without issue, so this is not a concern.

5. Distinguishing between a started task and a completed task

Sending a signal upon completion is sufficient for many tasks, but for long-running jobs it can be useful to know when they started as well. Some services support three types of signals:

  • Start: the task began running.
  • Success: the task finished successfully.
  • Failure: the task exited with an error.

This makes it possible to tell apart a task that never ran from one that started but got stuck or crashed midway through. For example, if a job that normally takes ten minutes sends a start signal but fails to send a success signal within the expected window, the monitor can alert you to a stalled execution.

The simplest implementation within a script chains the command and the success signal using &&:

# Inicio
curl -fsS --max-time 10 --retry 3 "$URL_INICIO"

# Trabajo y, solo si termina bien, señal de éxito
/opt/scripts/procesar_datos.sh && \
  curl -fsS --max-time 10 --retry 3 "$URL_EXITO"

To notify failures explicitly, you can introduce an error handler:

#!/usr/bin/env bash
set -Eeuo pipefail

source /opt/scripts/comun.sh   # log()

URL_INICIO="https://monitor.example.com/start/ID"
URL_EXITO="https://monitor.example.com/ping/ID"
URL_FALLO="https://monitor.example.com/fail/ID"

notificar() {
    curl -fsS --max-time 10 --retry 3 "$1" >/dev/null \
        || log WARN "No se pudo enviar la señal al monitor"
}

fallo() {
    local rc=$?
    trap - ERR
    notificar "$URL_FALLO"
    exit "$rc"
}

trap fallo ERR

notificar "$URL_INICIO"

# Si falla el envío de inicio, se registra la advertencia,
# pero la tarea continúa. El comportamiento del monitor
# dependerá del proveedor y de sus reglas de check-in.
/opt/scripts/procesar_datos.sh

# El trabajo terminó: a partir de aquí, un fallo del ping
# no debe reportarse como fallo de la tarea.
trap - ERR

curl -fsS --max-time 10 --retry 3 "$URL_EXITO" >/dev/null

The trap - ERR before the final ping is crucial. Without it, a network failure while sending the success ping would trigger the error handler, causing the monitor to receive a failure notice for a job that actually succeeded. If that final ping fails, the success signal simply never arrives, and the monitor will alert due to its absence—which is the correct outcome.

The endpoints shown are for illustration; follow the URLs and conventions required by your provider. Also remember that the ERR trap is not triggered by commands that fail inside an if, a while, or lists chained with && or ||, so it cannot replace explicit error handling in those situations.

Do not treat a start signal as proof that a process is still alive, either. Very long-running processes may need to send periodic progress signals or enforce a strict execution timeout.

6. Configuring intervals and tolerances

One of the most frequent mistakes when setting up this pattern is configuring overly aggressive thresholds. If a task runs daily at 2:00 AM and the alert is set to fire at 2:00 AM, any slight delay will trigger an unnecessary notification.

You need to account for:

  • The actual execution start time.
  • The normal duration of the task.
  • Occasional server load delays.
  • Network connectivity fluctuations.
  • Retry attempts to the monitoring endpoint.

Task duration is what people forget most often. The success ping arrives when the job ends, not when it starts: if the backup takes 20 minutes and the alert is set for 30 minutes after the scheduled start, you only have a 10-minute real safety buffer. The alert deadline should be calculated as: scheduled time + typical duration + grace period:

ParameterValue
FrequencyDaily
Scheduled time02:00
Typical duration20 minutes
Grace period30 minutes
First alert02:50

The interval must reflect how the process behaves in reality, not just the string written in the crontab. For a task running every five minutes, a ten-to-fifteen-minute grace period might be reasonable. For a nightly backup, a thirty-to-sixty-minute window often makes more sense.

Pay attention to daylight saving time changes and timezones as well. Cron operates on the server’s local system time, so your monitor must be configured to match it. Services that accept standard cron expressions paired with a specific timezone make this straightforward, allowing you to mirror your crontab line directly.

The goal is to steer clear of both extremes: alerting on every trivial delay, or waiting so long that an outage goes undetected for hours.

7. Avoiding false success signals

A heartbeat is only useful if it genuinely represents a successful run. Several common pitfalls can undermine your monitoring:

Sending the ping before completing the work.
If a script reports success as soon as it launches, the monitor will mark a job as healthy even if it crashes seconds later.

Sending the signal regardless of the outcome.
If a wrapper script contains the following lines without set -e enabled:

/opt/scripts/backup.sh
curl -fsS https://monitor.example.com/ping/ID

the second line will always execute, even if the backup failed. Bash will blindly continue to the next command regardless of the previous exit code.

If you want to chain both commands directly in crontab, use explicit conditional logic. Keep in mind that cron entries cannot be split across multiple lines using \: each entry must live on a single line.

0 2 * * * /opt/scripts/backup.sh && curl -fsS --max-time 10 --retry 3 https://monitor.example.com/ping/ID

Sending signals from an independent process.
If a separate cron job is responsible for sending the heartbeat, it may keep reporting green even when the primary task has stopped running altogether.

Hiding network errors.
Appending || true to start or failure pings is acceptable: if the success ping never arrives, the monitor will still alert on absence. However, the communication issue should be logged, such as with || log WARN "Failed to send signal", as shown in the notify function in step 5.

The rule is simple: the success signal must be tightly coupled to the actual outcome of the work, not merely to the existence of a process.

8. Applying heartbeat monitoring to your cron jobs

Suppose you have three scheduled tasks:

0 2 * * * /opt/scripts/backup.sh
*/15 * * * * /opt/scripts/sincronizar.sh
0 6 * * 1 /opt/scripts/reporte_semanal.sh

Each runs at a different cadence and requires its own monitoring setup:

TaskFrequencyWhat it must confirm
backup.shDailyBackup generated and validated
sync.shEvery 15 minutesSynchronization completed
weekly_report.shMondays at 6:00 AMReport generated successfully

You do not need to overhaul your cron setup to integrate this mechanism. Simply append the ping call to the end of each script, right after your validation checks pass.

You can also implement a shared wrapper script to centralize ping delivery, logging, and error handling. What matters most is that each task has its own unique endpoint, allowing you to pinpoint immediately which job failed to report.

If you use flock to prevent overlapping runs, ensure that the success signal is dispatched only after the locked section of work has fully finished.

9. What happens when the entire server goes down

If the server shuts down, loses network connectivity, or cron crashes, no tasks will be able to send their signals. The external monitoring service will wait, and once the deadline passes, it will trigger an alert. This is precisely the scenario that an on-box script could never report.

However, task monitoring does not replace infrastructure monitoring. You should continue to maintain separate checks for:

  • Server availability and ping.
  • Status of critical system daemons.
  • Disk space and inode usage.
  • CPU and memory consumption.
  • Network connectivity.

A task can technically keep pinging successfully while the server suffers from unrelated degradations. Both monitoring layers complement each other.

Putting it all together

With this article, the series covers all three pillars needed to properly monitor scheduled tasks:

MechanismWhat it detects
Error handlingA task that ran and failed
Heartbeat / Dead Man’s SwitchA task that stopped running entirely
Output validationA task that completed cleanly, but produced invalid or incomplete results

These patterns are not mutually exclusive. They reinforce each other and cover edge cases that, in isolation, would easily slip by unnoticed.

If you only have a few scheduled jobs, you can get started with a free external service and a quick curl call at the end of each script. You don’t need an elaborate observability stack just to verify that your backups, syncs, and reports are actually executing.

The fundamental goal is that your monitoring must never depend solely on the exact process it is trying to observe. Because there is a world of difference between getting an alert when something breaks, and getting an alert when something that was supposed to run simply never did.

Sometimes, the most dangerous issue is not a task that fails. It is a task that stops running and leaves no trace behind.