How to set up cronjobs for Symfony
About Symfony
Symfony is one of the most popular PHP frameworks. It also provides multiple components used by other frameworks like Laravel.
Running Symfony cronjobs, the old way
Unlike Laravel, Symfony doesn’t have a recommended way to run cronjobs.
Usually, you create a command using the make
bundle:
For example, to create the command app:cleanup
which will do the daily cleanup tasks,
make
will generate the file CleanupCommand
.
You can then update the file to do your tasks like this:
To run it once a day, at 5:30, you need to set up a cronjob on your server like this:
Everything is okay, until it’s not:
- Some error occurs, and it fails silently.
- You need to change the time pattern, and you forgot the crontab syntax (
minute hour day month weekday
by the way). - You need the script output from last Thursday, and there’s no way to retrieve it.
- You need to test-run it. Now log in to your server and work your magic.
- You changed the server, and you forgot to add the cronjob.
Some say cronjobs are not to be trusted, let’s add a cronjob monitoring service. Great, now you have 2 places to add the cron tab expressions. Every time you update your cronjobs, you’ll need to do it twice!
The better way to run Symfony cronjobs
A much simpler way to run cronjob is via the web.
Just create a route e.g. /cron/cleanup
like this:
Now you can visit the cronjob URL
with your browser to test your script.
If you still want to go with crontab, you can add it like this:
However, I’d recommend you to use a web cron like FastCron that offers:
- Full cron logs including starting time, total time, script output, etc.
- Email notifications when your cronjob fails or backs up again.
- A nice simple interface for you and your team.
- and many more features.
Give it a try now, it’s free!