Hello artisans,
How are you doing? In this tutorial, I will discuss with you Laravel Artisan Console Task Scheduling and Cron Job. If you don’t know about Cron job in laravel, don’t worry you are in the right place. In this Cron Job tutorial, I will try to explain Artisan Console Task Scheduling with an example.
Laravel Artisan Console Task Scheduling and Cron Job
What is Artisan Console?
Artisan Console is the name of the CLI included with Laravel. It provides a number of helpful commands for your use while developing your application/software. It is driven by the powerful Symfony Console component.
To see the list of all available Artisan commands, you can use the command in your terminal.
php artisan list

Laravel Artisan Console Task Scheduling and Cron Job
Here you can see a list of available artisan commands. You may think, How can I make my own custom artisan command?
Creating a custom artisan command you have to run this command.
php artisan make:command DeleteProduct
Read More : How to implement Redis Cache in Laravel 8.x
After then, Run this command, a new Command file has been created in App\Console\Commands directory.
App\Console\Commands\DeleteProduct.php
Now, in this class file, you may see two protected variables “signature”, “description” where you have to set up your command name and describe your command.
protected $signature = 'delete:product';
protected $description = 'Delete Low Price Products';
Now you have to define your logic in handle() method like this.
Laravel Artisan Console Task Scheduling and Cron Job
public function handle()
{
$products = Product::where('price','<', 300)->delete();
$products ? $this->info('Delete') : $this->info('Not Delete');
return 0;
}
in this handle I set up and logic which is to delete products that price under 300. (You can define your own logic)
Next, Now you have to register for this command App\Console\Kernel class. go there and register your command in the $commands array.
App\Console\Kernel
protected $commands = [
DeleteProduct::class
];
then you have to set a schedule for how many times you want to run your command.
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
$schedule->command('delete:product')->everyMinute();
}
You can add more time like everyTwoMinutes(), everyThreeMinutes(), everyFiveMinutes(), everyThirtyMinutes(), hourly(), hourlyAt(17), daily().
now run this command in your terminal.
php artisan schedule:work
Every 1 minute run your custom artisan command automatically. Hope It will help you.
Read More: Send SMS in mobile using nexmo from laravel application