Monitory
← All guides

Guides

How to monitor cron jobs and scheduled tasks

Catch backups, reports and jobs that silently stop running, with heartbeat pings and a Laravel scheduler example.

The problem with silent failures

Cron has no built-in alert. A backup that never ran, a report that was never sent or a queue that was never processed produces no error, because nothing ran at all. You find out when you need the backup.

Heartbeat monitoring

The fix is to flip the check around. Instead of looking for errors, your job calls a URL when it runs. If the call does not arrive on time, you get an alert.

Set it up

  1. Create a scheduled task, then set how often it should run and a grace period, five minutes by default, to allow for slow runs.
  2. Copy its ping URL and call it from the job:
0 * * * * /usr/local/bin/backup.sh && curl -fsS "<ping-url>"
  1. To also catch failures and runs that never finish, signal the start and report errors:
curl -fsS "<ping-url>/starting"
/usr/local/bin/backup.sh
status=$?
if [ "$status" -eq 0 ]; then
  curl -fsS "<ping-url>"
else
  curl -fsS "<ping-url>/failed?exit_code=$status"
fi

You can also send runtime, memory and failure_message as query parameters. They are stored with each run.

In Laravel

The scheduler can make these calls for you:

Schedule::command('backup:run')
    ->daily()
    ->pingBefore('<ping-url>/starting')
    ->thenPing('<ping-url>')
    ->pingOnFailure('<ping-url>/failed');

What triggers an alert

  • The job reports a failure.
  • A job that started does not finish within the grace period.
  • No ping arrives within the expected interval plus the grace period.

Keep reading