
How to use Cron Job in laravel 10, In this tutorial we will see how to use a cron job in Laravel 10 step-by-step with fully exampled. Scheduling of cron jobs.
Why do we use Crons Job? How do you set up cron jobs and the benefits of cron jobs in Laravel 10? As we know many times we need to send emails and notifications to users automatically so we need to refresh our system after some time.
I will explain everything in a simple way. I will show you some logic you can also make your own logic with cron jobs. Follow the steps to learn using Cron Jobs in Laravel 10.
Step 1: Project creating
We need a fresh project to perform our task so run the given command to create a project.
Composer require Laravel/Laravel CronJobs
Or
Laravel new CronJobs
Step 2: Command Making
So we need a command to execute our Cron job, and run the given command to make a new command.
Php artisan make:command DemoCron –command=demo:cron
Then we need to make some changes in our created commands. Now open the files
App/Comsole/Commadns/DemoCron.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
class DemoCron extends Command
{
protected $signature = 'demo:cron';
protected $description = 'Command description';
public function handle(): void
{
info("Cron Job running at ". now());
$response = Http::get('https://jsonplaceholder.typicode.com/users');
$users = $response->json();
if (!empty($users)) {
foreach ($users as $key => $user) {
if(!User::where('email', $user['email'])->exists() ){
User::create([
'name' => $user['name'],
'email' => $user['email'],
'password' => bcrypt('123456789')
]);
}
}
}
}
}
Step 3: Task Scheduler registration
So we need to define our command in Kernel.php. And also a time in which you want to execute a command.
Commands |
Description |
everyMinute() |
Command Execute every minute |
everyFiveMinutes() |
Command Execute after every five minutes |
everyTenMinutes() |
Command Execute after every ten minutes |
everyFitennMinutes() |
Command Execute after every fifteen minutes |
everyThirtyMinutes() |
Command Execute after every thirty minutes |
Hourly() |
Command Execute after every hour |
hourlyAt(17) |
Command Execute after one hour and 17 minutes |
App/Console/Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule): void
{
$schedule->command('demo:cron')
->everyFiveMinutes();
}
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
Step 4: Testing of Cron Job
Our Cron job is ready now so run our system and test it is working properly or not. Run the given command to check:
Php artisan schedule:run
So open the log file to check command is working or not.
Storage/logs/Laravel.php
No Comments Yet.