Laravel Scheduler
Jun
14
2019

Laravel Scheduler

A brand new feature in Laravel Devlopment is an Artisan scheduler. This is designed to simplify tasks that need to be scheduled. All that is required is setting up one cron job that calls php artisan schedule:run and have it run every minute.

If we want to schedule tasks that will be executed every so often, we need to edit the Crontab. Crontab is a file that contains a list of scripts that will run periodically. Cron is a task scheduler daemon which runs scheduled tasks at specific intervals. Cron uses the configuration file called crontab, also known as cron table, to manage the scheduling process. Crontab contains cron jobs, each related to a specific task. Cron jobs are composed of two parts.

We use the make: console Artisan command to generate a command class skeleton to work with.

Laravel Scheduler

The above command will create a class named file of the same name in the app/Console/Commands folder.

We have also picked a name for the command via the command option. It is the name that we will use when calling the command. Now, open that command file

/**
* The console command description.
*
* @var string
*/
protected $description = 'Send an email;

We have just changed the description of the command. Now, we need to register this command inside app >> Console >> Kernel.php file.

protected $commands = [
'App\Console\Commands\ClassName,
];

Go to the terminal and run the following command.

php artisan list

You can see in the list that your newly created command has been registered successfully.

Here is an example of a fictional task to clear the cache every hour:

$schedule->command('cache:clear')
->hourly()
->sendOutputTo($filePath)
->emailOutputTo(abc@example.com');

It doesn’t end there. You can also call class methods:

$schedule->call('SomeClass@method')->dailyAt('10:00');
Take a look at the different scheduling methods available:

->hourly()
->daily()
->at($time) // 24 hour time
->dailyAt($time)
->twiceDaily()
->weekdays()
->mondays()
->tuesdays()
->wednesdays()
->thursdays()
->fridays()
->saturdays()
->sundays()
->weekly()
->weeklyOn($day, $time)
->monthly()
->yearly()
->everyFiveMinutes()
->everyTenMinutes()
->everyThirtyMinutes()
->days() // Days of the week.
->cron(‘* * * * *’) Run the task on a custom Cron schedule

So * * * * * means every minute of every hour of every day of every month and every day of the week.

* * * * * command to execute

┬ ┬ ┬ ┬ ┬

│ │ │ │ │

│ │ │ │ │

│ │ │ │ └──day of the week (0 – 7) (0 to 6 are Sunday to Saturday or use names, 7 is Sunday, the same as 0)

│ │ │ └────────── month (1 – 12)

│ │ └─────────────── day of the month (1 – 31)

│ └──────────────────── hour (0 – 23)

└───────────────────────── min (0 – 59)