Laravel Cron Job from Command Line Interface(CLI) and Schedular
Laravel Command line interface (CLI)
Create a Command class from command running:
php artisan make:console yourCommandName
it will be under app/console/Commands/ yourCodName.php
I am going with email scheduler. So, mine is
php artisan make:console sendEmail
in app/console/Commands/sendEmail.php
For running it should be added in Kernel (app/console/Kernel.php) . So, you have to add created class in Kernel.php.
Add inside protected command as;
protected $commands = [
\App\Console\Commands\sendEmail::class,
];
If you have previous one then add this line. Yours as example will be:
protected $commands = [
\App\Console\Commands\yourCommandName::class,
];
Inside the Command class that you have just created. Configure like:
protected $signature = 'sendemail';
which will be custom name for your command. You can use it to run as
php artisan sendemail
protected $description = 'Email sending Command as schedular';
This will describe your command.
Inside handle function created in Command class, you will write your code.
Mine is like this:
public function handle()
{
Mail::send(view_file_that_you_want_to_send', ['key' => 'value'], function($message)
{
$message->to('[email protected]', 'Name of the Email')->subject('Subject of email');
});
}
All you have to this for command.
You can check it for checking:
public function handle()
{
echo ‘This is check only’;
}
Now you have to register it in schedule as:
protected function schedule(Schedule $schedule)
{
$schedule->command('sendemail')
->hourly();
}
Now you have your schedule which is written as Command for email send.
Different methods available for scheduler are as follows:
- ->hourly()
- ->monthly()
- ->yearly()
- ->everyFiveMinutes()
- ->daily()
- ->sundays()
- ->weekly()
- ->weeklyOn($day, $time)
- ->at($time) // 24 hour time
- ->dailyAt($time)
- ->twiceDaily()
- ->weekdays()
- ->everyTenMinutes()
- ->everyThirtyMinutes()
- ->days() // Days of the week.
- ->mondays()
- ->tuesdays()
- ->wednesdays()
- ->thursdays()
- ->fridays()
- ->saturdays()
Enjoy.