DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Monitor AI Models Without Drowning in Alerts
  • Debugging Distributed Flight Search: What Logs Alone Won’t Tell You
  • How Event-Driven Ansible Works for Configuration Monitoring
  • Using Event-Driven Ansible to Monitor Your Web Application

Trending

  • Exactly-Once Stream Processing With Apache Flink
  • As AI Agents Multiply, Repository Access Could Become an Infrastructure Problem
  • Function Calling: Responses API vs Chat Completions
  • Running an OpenStreetMap Tile Server for the Whole Planet on Modest Hardware

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Monitoring and Observability
  4. The Cron Job Stopped and Nothing Turned Red

The Cron Job Stopped and Nothing Turned Red

Cron jobs fail silently. No exception, no 500, nothing turns red. You only notice when the data is already stale. Here’s how to catch that before it becomes a problem.

By 
Mattias Geniar
·
Nov. 30, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
179 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The Job Nobody Was Watching

We had a crucial job that watched our paid ad spend. It paused underperforming campaigns and moved their budget to the campaigns that performed better. Then the API key it used expired. Nothing was monitoring that cron job, so we assumed everything was running just fine. In the end, it cost us quite a bit of money: the underperforming ads were never paused, and they just kept running and collecting clicks.

The annoying part is that everything around it looks fine. The web server answers requests. The database accepts connections. The status page is green. Meanwhile, the scheduled task that creates backups, imports orders, expires sessions, or generates invoices has quietly stopped.

Cron fails by doing nothing. Sometimes the job never starts. Sometimes it starts, can't do its work, and tells nobody. There's no HTTP 500, because no HTTP request was involved. There may not even be a log line to grep for. That happens when the crontab is removed, the cron daemon stops, or the command can't be found.

So you have to monitor for something that didn't happen. The job checks in. Silence is the alert.

Why Your Existing Checks Miss It

An HTTP uptime check answers a narrow question: can I connect to this URL and get an acceptable response? The homepage can return 200 while the weekday job scheduled for 02:17 has been dead for a week.

An ICMP ping is narrower still. The kernel answers a ping even when cron is stopped, the application is broken, or the backup script has lost its credentials.

Application health endpoints are useful, but they report what the running application says about itself. A healthy JSON response isn't proof that a separate scheduled task ran last night.

All three checks ask whether something is there. A scheduled job needs the opposite question: did the job that should have run actually run?

Silent jobs accumulate in predictable places: inherited crontabs, CMS plugins, forgotten Windows servers, framework schedulers, and scripts that one person configured years ago.

The biggest risk lies in the type of cron job that only occasionally reports something to you. For instance, when everything is fine, the scheduled task does nothing. Otherwise, it sends you an email with an overview of the items that need fixing. It's quite common to receive nothing for weeks on end, and then an email with actionable items once every few weeks. If that email never comes, it looks like everything is fine and nothing needs your attention. But maybe the scheduled task was just broken.

The Heartbeat Pattern

A heartbeat works the other way around. The monitor doesn't poll the process, which may only exist for a few seconds. The process calls the monitor.

Each job gets a unique URL. The job requests that URL after it finishes successfully. The receiver stores the timestamp and compares it with the expected schedule. If the next request does not arrive within the allowed window, it sends an alert.

Plain Text
 
scheduled job
     |
     | HTTP request after each run
     v
unique ping URL
     |
     | timestamp compared with schedule
     v
heartbeat monitor
     |
     | expected window passes without a ping
     v
alert to the job owner


Use one URL per job, not one URL per server. A message saying that server-12 missed a heartbeat still leaves you searching through its crontabs. A message naming nightly-database-backup gives you somewhere to start.

The receiver doesn't need to be complicated. It can be a small self-hosted endpoint that records timestamps, or any heartbeat service.

Step 1: The One-Line Version

The smallest useful implementation is a successful command followed by a request:

Plain Text
 
17 2 * * 1-5 /usr/local/bin/backup.sh && /usr/bin/curl -fsS -m 10 --retry 3 https://<monitor>/ping/<job-id>


The && matters. It runs curl only if backup.sh exits with status zero. With ; instead, the ping goes out even when the backup fails. The monitor records a success for a backup that failed.

The curl flags are there for unattended runs. -f treats HTTP error responses as failures. -sS hides the progress meter but keeps error messages. -m 10 limits the total request time. A slow receiver can't leave the job hanging. --retry 3 handles a short network interruption.

Cron normally starts commands with a minimal environment. Its PATH may differ from the one in your interactive shell. Shell initialization files may never run. Use absolute paths for both the job and curl.

Cron jobs don't always cleanly survive server migrations. If you blindly copy scheduled tasks from one server to a new one, but don't account for changed paths or directories, or even a different user that runs the code, the scheduled task may never execute correctly.

The one-line version works, but it's incomplete. A failed job and a job that never started both stay silent until the monitoring window runs out.

Step 2: Start and Finish Pings

For a job that runs longer than a few seconds, send one request when it starts and another when it exits. This gives you a runtime. It also tells "never started" apart from "started but never finished."

A Bash wrapper can do this without duplicating the exit handling:

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

ping_url="https://<monitor>/ping/<job-id>"
started_at=$(/usr/bin/date +%s)

/usr/bin/curl -fsS -m 10 --retry 3 "${ping_url}/start" || true

finish() {
    local exit_code=$?
    local finished_at
    local runtime

    finished_at=$(/usr/bin/date +%s)
    runtime=$((finished_at - started_at))

    trap - EXIT
    set +e

    if (( exit_code == 0 )); then
        /usr/bin/curl -fsS -m 10 --retry 3 \
            -X POST \
            --data-urlencode "exit_code=${exit_code}" \
            --data-urlencode "runtime_seconds=${runtime}" \
            "${ping_url}" || true
    else
        /usr/bin/curl -fsS -m 10 --retry 3 \
            -X POST \
            --data-urlencode "exit_code=${exit_code}" \
            --data-urlencode "runtime_seconds=${runtime}" \
            "${ping_url}/fail" || true
    fi

    exit "${exit_code}"
}

trap finish EXIT

/usr/local/bin/backup.sh


The || true on the start request is deliberate. If the monitor is down, I still want the backup to run. A monitoring failure shouldn't turn into a backup failure. The EXIT trap keeps the job's original exit code and calculates its runtime. It sends the matching ping, then exits with that same code.

If another start arrives before the earlier run finishes, you may have overlapping jobs, a stuck process, or a timeout elsewhere in the stack.

Step 3: Fail Loudly, Not Late

Without an explicit failure request, you only find out about a crash once the grace period expires. That is why the one-line && example is not enough for every job. A failed backup sends no ping. At first it looks the same as a backup that never ran.

Send failures to /fail immediately. Include enough context for a first look: the exit code, the runtime, and a few lines of stderr.

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

ping_url="https://<monitor>/ping/<job-id>"
started_at=$(/usr/bin/date +%s)
stderr_file=$(/usr/bin/mktemp)

/usr/bin/curl -fsS -m 10 --retry 3 "${ping_url}/start" || true

finish() {
    local exit_code=$?
    local finished_at
    local runtime
    local stderr_tail
    local endpoint

    finished_at=$(/usr/bin/date +%s)
    runtime=$((finished_at - started_at))
    stderr_tail=$(/usr/bin/tail -n 20 "${stderr_file}")
    endpoint="${ping_url}"

    if (( exit_code != 0 )); then
        endpoint="${ping_url}/fail"
    fi

    trap - EXIT
    set +e

    /usr/bin/curl -fsS -m 10 --retry 3 \
        -X POST \
        --data-urlencode "exit_code=${exit_code}" \
        --data-urlencode "runtime_seconds=${runtime}" \
        --data-urlencode "stderr=${stderr_tail}" \
        "${endpoint}" || true

    /usr/bin/rm -f "${stderr_file}"
    exit "${exit_code}"
}

trap finish EXIT

/usr/local/bin/backup.sh 2>"${stderr_file}"


"The backup was missed" is vague. "The job ran for 12 minutes and exited 137" is actionable. Exit code 137 is 128 plus 9, meaning the process received SIGKILL. The out-of-memory killer is a common cause. Check memory pressure first.

It's not uncommon for a PHP scheduled task to run into a segfault if you're running an older PHP version. Without actionable monitoring, those errors simply disappear. They don't even end up in your PHP error log, because PHP crashed before it could write one. The wrapper above still catches it: the failure ping arrives with exit code 139, which is 128 plus 11, SIGSEGV.

Don't ship the whole log. The last 20 lines are usually enough for a first clue. The full log can stay on the host.

Step 4: Describing the Schedule Honestly

There are two common scheduling models. The first expects a check-in at least once every N minutes. The second evaluates an actual cron expression.

Intervals work for jobs that run continuously or at a fixed frequency. They don't fit calendar schedules. A job scheduled for 02:17 from Monday through Friday will look late every Saturday if the receiver expects a request every 24 hours.

For calendar-based jobs, give the monitor the same cron expression the scheduler uses. Give it the time zone too. A cron expression without a time zone is ambiguous, especially when the server, application, and monitoring receiver use different defaults.

Daylight saving time makes this worse. In most of Europe, the clocks jump from 02:00 to 03:00 in spring. A 02:17 run doesn't exist that day. In autumn, the hour from 02:00 to 03:00 happens twice. What cron does with that depends on the implementation. Your monitor has to agree with it.

Leap seconds used to cause issues too. Today, systems mostly handle them fine. But more than a decade ago, I remember that the occasional server crash during a leap second was not uncommon. The server would often reboot on its own, but whatever was scheduled to run during the reboot never executed. Cron doesn't catch up on missed runs, so only a heartbeat would have told you.

A grace period sets how late a check-in may be before the job counts as missed. It must cover both late starts and slow runs. A backup that normally takes 90 seconds but sometimes needs six minutes should not alert at the two-minute mark.

Set the grace period from observed runtimes, with room for the slowest runs. Do not copy one value across every job.

In our own system, we have jobs that do monthly reporting for our clients. Every client who opts in gets a monthly uptime report, sent either to the owner of the account or directly to their own clients.

It's never quite clear how long generating those uptime reports will take: if a site had more downtime that month, its report takes longer. So that job has a quite generous grace period to account for fluctuations. It's also the type of job that keeps taking longer as more customers sign up and use the service, so the fluctuations might increase over time too. That's a grace period you have to revisit every now and then.

Step 5: Send the Alert to Whoever Can Fix It

A missed heartbeat that lands in a shared inbox nobody reads at 02:17 is the same as no heartbeat.

Assign an owner to each job. Route the alert to the person or team that can inspect and restart it. The person responsible for a Windows task in one department may have no access to another team's framework scheduler.

The alert should name the exact task, host, expected time, and last successful check-in. Make the name recognizable to the operator. Internal identifiers are fine for machines. job-7f3a doesn't tell a person what broke.

Throttle repeats, too. One silent job should not produce an alert every minute. Notify when it becomes late. Repeat at an interval you choose, if needed. Resolve the incident when a valid check-in arrives.

Beyond crontab

The same pattern works anywhere a task can make an HTTP request: Windows Task Scheduler, queue workers, framework schedulers, deployment scripts, and one-off maintenance commands.

A short PowerShell task can run a command, verify its exit status, and send the success heartbeat:

PowerShell
 
& "C:\Scripts\backup.exe"

if ($LASTEXITCODE -ne 0) {
    throw "backup.exe exited with code $LASTEXITCODE"
}

Invoke-WebRequest `
    -Uri "https://<monitor>/ping/<job-id>" `
    -TimeoutSec 10 `
    -UseBasicParsing


This matters most on servers you inherited and don't fully control. Installing extra software there is often not an option. An HTTP request from the shell or runtime that's already on the box usually is. You still have to check three things: the request tool exists, credentials are handled safely, and outbound network access is allowed.

If you're programming in PHP and you define your scheduled tasks in the framework, either in Symfony or in Laravel, the scheduler can send these pings for you. Laravel has start, success, and failure pings built in:

PHP
 
// routes/console.php
use Illuminate\Support\Facades\Schedule;

Schedule::command('backup:run')
    ->weekdays()
    ->at('02:17')
    ->timezone('Europe/Brussels')
    ->pingBefore('https://<monitor>/ping/<job-id>/start')
    ->pingOnSuccess('https://<monitor>/ping/<job-id>')
    ->pingOnFailure('https://<monitor>/ping/<job-id>/fail');


For Symfony, zenstruck/schedule-bundle has similar ping hooks. And there are open-source packages, like spatie/laravel-schedule-monitor, that automatically register all your scheduled tasks with your heartbeat monitor and keep them in sync. That doesn't even need a single extra line of code in your task definitions.

What a Heartbeat Can't Tell You

A heartbeat proves the job got far enough to send its check-in.

It doesn't prove the backup can be restored. It doesn't prove the report has the right rows, or that the import matched your business rules. A command can exit zero after producing an empty file, skipping half its input, or writing corrupt output.

Pair the heartbeat with validation that fits the job. Restore backups on a schedule and test the restored data. Check that an export is non-empty and has a plausible row count. Verify a checksum after transferring a file. Make an import exit non-zero when required records are missing.

Validation has to change the job's exit status. If the script detects bad output but still exits zero, the heartbeat reports a success.

If you're just getting started, you don't need a full validation suite on day one. Differentiating between what you consider the good outcome and the bad outcome, regardless of what that bad outcome is, is already powerful: it alerts you to the problem and lets you investigate deeper. Once that works, add metadata to the failure ping, like in Step 3, so it carries the exact failure message: why the task didn't do its work, either because its data was invalid or because an exception was thrown midway.

Rollout Checklist

Start with an inventory. Check every user's crontab on each host, system-wide cron directories, Windows Task Scheduler, framework schedulers, queue systems, and CI schedules. Undocumented jobs are the ones most likely to stay silent.

For each job:

  • Assign one unique ping URL.
  • Use &&, not ;, for the basic success-only form.
  • Put timeouts and retries on every curl request.
  • Use absolute paths in crontab.
  • After a server migration, check the paths and the user that runs each job.
  • Add start, finish, and failure requests for jobs that take more than a few seconds.
  • Configure the real cron expression and the time zone the scheduler actually uses.
  • Set the grace period from actual runtime observations.
  • Assign an owner who can investigate the alert.

Test failure as well as success. Temporarily use a command that exits non-zero and confirm that the failure path runs. Then disable the schedule on purpose and check that an alert arrives after the expected window.

Closing

I've seen scheduled tasks fail in spectacular ways: from an expired SSL certificate on a remote API that made the task's curl call fail, all the way to segfaults, race conditions, time zone issues, faulty deploys — you name it.

It's easy to fall into the trap of thinking that a scheduled task, once defined, will keep running forever. But chances are neither your code nor your infrastructure is static. It moves; it evolves. You iterate based on market demand; you change the application. You have to monitor all these moving pieces, and scheduled tasks are definitely one of them.

Heartbeat (computing) Monitor (synchronization)

Opinions expressed by DZone contributors are their own.

Related

  • How to Monitor AI Models Without Drowning in Alerts
  • Debugging Distributed Flight Search: What Logs Alone Won’t Tell You
  • How Event-Driven Ansible Works for Configuration Monitoring
  • Using Event-Driven Ansible to Monitor Your Web Application

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook