If you’re relying on cron jobs with your app, making sure they run correctly every single time is a must.
No one wants their scheduled database backup or an email campaign to fail and not know about it.
In this post, you’ll learn how to set up a system that automatically monitors your cron jobs and alerts you in case of any issues.
How to set up cron monitoring
You need a monitoring tool like Better Stack to do this, which is now used by over 150.000 developers.
⚖️ What’s the difference: Cron job vs. heartbeat monitoring
There are, in most cases the same. Cron job monitoring specifically refers to monitoring the specific job scheduler: cron. Heartbeat monitoring is a general name for monitoring any software system or device by expecting a regular “heartbeat” (usually a GET request) on a dedicated endpoint.
Free method (up to 10 monitors)
Sign up for Better Stack, go to the Heartbeats tab, and create a new heartbeat. There you can create up to 10 monitors for free.
You can specify how often your cron runs. If it’s an hourly database, make it every hour. The grace period is there to prevent false positives - in case something runs a little slower.
Then pick how you want to get alerted if something goes wrong.
Now copy the unique monitor URL and add a simple HEAD, GET, or POST request to it at the end of the cron job script.
Here is an example of how this would look like in a backup script.
set -o errexit
set -o xtrace
time dokku postgres:export uptime > "$file"
/usr/local/bin/aws s3 cp "$file" s3://uptime-dbbackups/
# you get this URL in the Uptime dashboard
What happens here is that the Heartbeat URL we've created above expects a GET or POST request every day since having made the first request.
If the code above fails, our background job won't make the request to the Heartbeat URL. In that case, the heartbeat will alert the current on-call person and create an Incident.
Paid method (unlimited monitors)
To have more than 10 monitors, Sign up for Better Stack and choose any of the paid plans. Paid plan also includes other features, including regular uptime monitoring, incident alerting with on-call and status pages.
How to run cron jobs everywhere and anytime
Here are quick tutorials how to set up cron jobs in different environments:
Jenda leads Growth at Better Stack. For the past 5 years, Jenda has been writing about exciting learnings from working with hundreds of developers across the world. When he's not spreading the word about the amazing software built at Better Stack, he enjoys traveling, hiking, reading, and playing tennis.
Are you a developer and love writing and sharing your knowledge with the world? Join our guest
writing program and get paid for writing amazing technical guides. We'll get them to the right
readers that will appreciate them.