iOS + Web Developer | Indie | Writer at http://www.valentinourbano.com | Music, SW | 🇪🇺 |
Laravel includes ‘Scheduling’ to handle cron jobs. You can easily schedule them from inside Laravel using an expressive and easy to use syntax.
The “App\Console\Kernel” class handles all the scheduling in Laravel.
You should NOT put any logic in here though. This method should only be used to set the schedule. To actually define what to run you should create a new artisan command for each task you want to run. You can create a new command by running
php artisan make:command. If your command is called "HourlyUpdate" run
php artisan make:command HourlyUpdate.
It will create a new file inside app/Commands. Open it and edit its “signature”. It will be the name used from the kernel class and the command line to call your task.
Edit its description. It should be a human-readable explanation of the purpose of the command.
Edit its handle. The handle is the method that executes the task.
Now open “Kernel.php” in “app/Console” and add our newly created class to the “commands” array:
Edit “schedule” to schedule our tasks. For example
everyMinute() will run the task every minute while
everyHour() will run it every hour. You can also specify a specific day of the month with
monthlyOn(1, '00:01') . To find a list of all available options check [the official documentation]
You can also tell Laravel to print the output of the task to a file
For our example, we’ll be running our task at the beginning of every month. We’ll also be saving the output to a file for debugging purposes and we want to make sure that a task doesn’t start if there is another task running.
You can test your cron job by manually calling it from the Terminal. You can list all your custom action and the default artisan actions using
It will return a list of all available actions.
“monthly:quota” is our custom action. We can call it using
php artisan monthly:quota.
Finally, you need to actually go to the crontab in your Linux installation and tell the system to call Laravel every minute.
Laravel will than evaluate all the cronjobs and decide if it needs to schedule something for execution or not. If it doesn’t need to perform any action it will return straight away.
Open the crontab using the Terminal. It is usually located in
/etc/crontab and add the following line, making sure to write in the path to your Laravel Project.
We’re also ignoring the output since Laravel already allows us to configure what to do with the output.
As always with schedules be mindful of different time zones.
Laravel makes it extremely easy to schedule tasks to run at specific intervals with an immediate syntax and many configuration options.
I’ve just launched Markdown Love in less than 24 hours, an API to turn any article on the web into markdown removing all the clutter, using Laravel.