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
- Create a scheduled task, then set how often it should run and a grace period, five minutes by default, to allow for slow runs.
- Copy its ping URL and call it from the job:
0 * * * * /usr/local/bin/backup.sh && curl -fsS "<ping-url>"
- 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.