Laravel 10 Cron Job Task Scheduling Tutorial
Hey Folks,
In this tutorial, I will show you laravel 10 cron job tutorial. This article goes in detailed on laravel 10 cron job task scheduling. I explained simply about how to create cron job in laravel 10. This article goes in detailed on how to make a cron job in laravel 10. So, let us dive into the details.
Why do we have to use a cron job? and what is a benefit to using cron jobs in laravel 10 and how to set up cron jobs in laravel 10?, If you have this question then I will explain why. Many times we need to send notifications or send emails automatically to users to update property or products. So at that time, you can define some basic logic for each day, hour, etc can run and send email notifications.
Here, I will give you a very simple example. we will create a cron job command to get users from API and create new users in our database. we will set tasks automatically done by every minute task. You can write your own logic on command. I will also show you how to set up a cron job in server with laravel 10. so let's follow the below step to do this example.
Step for Laravel 10 Cron Job Task Scheduling Example
- Step 1: Install Laravel 10
- Step 2: Create New Command
- Step 3: Register as Task Scheduler
- Step 4: Run Scheduler Command For Test
- Laravel Cron Job Setup on Server
Follow the below steps:
Step 1: Install Laravel 10
This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Create New Command
In this step, we need to create our custom command. custom command will execute with task scheduling scron job. so, let's run bellow command to create new custom command.
php artisan make:command DemoCron --command=demo:cron
Now make some changes on Command file.
app/Console/Commands/DemoCron.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
class DemoCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle(): void
{
info("Cron Job running at ". now());
/*------------------------------------------
--------------------------------------------
Write Your Logic Here....
I am getting users and create new users if not exist....
--------------------------------------------
--------------------------------------------*/
$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: Register as Task Scheduler
In this step, we need to define our commands on Kernel.php file with time when you want to run your command like as bellow functions:
->everyMinute(); | Run the task every minute |
->everyFiveMinutes(); | Run the task every five minutes |
->everyTenMinutes(); | Run the task every ten minutes |
->everyFifteenMinutes(); | Run the task every fifteen minutes |
->everyThirtyMinutes(); | Run the task every thirty minutes |
->hourly(); | Run the task every hour |
->hourlyAt(17); | Run the task every hour at 17 mins past the hour |
->daily(); | Run the task every day at midnight |
->dailyAt(’13:00′); | Run the task every day at 13:00 |
->twiceDaily(1, 13); | Run the task daily at 1:00 & 13:00 |
->weekly(); | Run the task every week |
->weeklyOn(1, ‘8:00’); | Run the task every week on Tuesday at 8:00 |
->monthly(); | Run the task every month |
->monthlyOn(4, ’15:00′); | Run the task every month on the 4th at 15:00 |
->quarterly(); | Run the task every quarter |
->yearly(); | Run the task every year |
->timezone(‘America/New_York’); | Set the timezone |
app/Console/Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
$schedule->command('demo:cron')
->everyMinute();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
Step 4: Run Scheduler Command For Test
now we are ready to run our cron, so you can manually check using following command of your cron. so let's run bellow command:
php artisan schedule:run
After run above command, you can check log file where we already print some text. so open you your log file it looks like as bellow:
storage/logs/laravel.php
[2022-03-01 03:51:02] local.INFO: Cron Job running at 2022-03-01 03:51:02
[2022-03-01 03:52:01] local.INFO: Cron Job running at 2022-03-01 03:52:01
[2022-03-01 03:53:02] local.INFO: Cron Job running at 2022-03-01 03:53:02
Laravel 10 Cron Job Setup on Server
Here, i will show you how to setup cron job command on server. you need to install crontab on server. if you are using ubuntu server then it already installed. so let's run bellow command and add new entry for cron job.
crontab -e
Now, add bellow line to crontab file. make sure you need to set your project path correctly on it.
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Now, you can check on server as well.
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 10 Send Email using Queue Example
- Laravel 10 Guzzle Http Request Example
- Laravel 10 Change Date Format Examples
- Laravel 10 Yajra Datatables Tutorial Example
- Laravel 10 Markdown | Laravel 10 Send Email using Markdown Mailables
- Laravel 10 REST API Authentication using Sanctum Tutorial
- Laravel 10 Ajax Image Upload Example
- Laravel 10 Mail | Laravel 10 Send Mail Tutorial
- Laravel 10 Create Custom Helper Functions Example
- Laravel 10 Authentication using Jetstream Tutorial
- Laravel 10 Import Export Excel and CSV File Tutorial
- Laravel 10 Generate PDF File using DomPDF Example
- Laravel 10 Image Upload Example Tutorial