In this tutorial we're going to learn how to setup and use scheduled tasks with Laravel to perform the same tasks on a regular timescale.
To use scheduled tasks in Laravel it will use your server cron jobs. What makes this different to just setting up a cron jobs is that Laravel will only have on entry in your cron job setup.
Before if you want to create a scheduled task you will have to setup each task as it's own cron job, with Laravel you only need to do this once.
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Define Jobs
To define your scheduled jobs you need to use the app/Console/Kernel.php
file and add a method for schedule
.
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
}
There are a few ways you can run different bits of code off the Schedule
class using the following methods.
- command - To run an artisan command
- call - To run a callback function
- job - To dispatch a specific job.
- exec - To execute a specific shell command
When Tasks Will Run
You can fully customise when to run the command defined on the scheduler. You can select to define a cron settings, run every X minutes, run hourly, run daily, run weekly, run monthly etc.
Running a Command Daily
Below is the example code you will use to run an artisan command every day.
<?php
namespace App\Console;
use App\Console\Commands\ArtisanCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
ArtisanCommand::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command(ArtisanCommand::class)->daily();
}
}
This uses the $schedule
class to run a command ->command($commandClassName)
then we set it to run ->daily()
, which will run everyday at midnight.