Lesson learned: Monitor your Cronjobs
Scheduling tasks in Laravel is an easy and powerful way of adding a bit of automation to your project. Do you want to clear your logs every night, update cached data from an external API every hour, or maybe ping a URL every five minutes? Just add a few lines of code to your Kernel and you're good to go.
Check out the official documentation if you haven't used cronjobs before.
But what happens when your cronjob stops working all of a sudden? Normally Laravel throws errors whenever anything goes wrong, and since those are sent straight to our Discord server we can react quickly and fix most issues before our clients even notice them. But a process that never runs will also never throw an error, so you don't get that alert.
When Cronjobs fail
We just learned this the hard way with one of our clients a few months ago. Their site uses a cronjob to check an API for new reports generated for their users and e-mails those directly to them.
Everything had been running smoothly for two years when suddenly we started getting complaints about users not receiving their requested reports. Of course the error logs were the first thing I checked, and to my surprise those were clean.
It took a few minutes for me to figure out that the scheduler was no longer running, meaning our cronjob simply hadn't been triggered in almost a week. Reports had been piling up, users were getting frustrated, and we had no idea since their was no error output or alert at all.
In the end it was a quick fix, but it got us thinking: how do we prevent this in the future? It's easy to catch when something throws an error - but how can we be alerted if a function just never runs?
Time for a Monitoring Tool
It was clear we needed a solid and reliable solution for this to make sure it never happens again. Once you do your research you'll find you're not the first to run into this issue - and there are 1001 monitoring tools out there allowing you to monitor your cronjobs.
While I'm sure all of them work just fine, I wanted a solution that would work with Laravel with minimal setup - which is why we ended up signing up with Oh Dear. It definitely helped that it's developed by Freek Van der Herten, whose contributions to the Laravel ecosystem can't be overstated.
In the end the changes to our code were minimal, we just need the scheduled task to also ping Oh Dear after running.
It's not a lot of work and the monthly cost is also negligible - but it could save you from a lot of headaches and angry clients in the future. So feel free to learn from my mistakes and sign up for a monitoring solution before you regret it.