Laravel 11 Cron Job Task Scheduling Tutorial

By Hardik Savani September 30, 2024 Category : Laravel

In this post, I will show you step by step how to set up cron job task scheduling in Laravel 11 application.

Why do we have to use a cron job? And what are the benefits of using cron jobs in Laravel 11 and how to set up cron jobs in Laravel 11? If you have these questions, then I will explain why. Many times we need to send notifications or emails automatically to users to update property or products. So at that time, you can define some basic logic for each day, hour, etc., to 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 an API and create new users in our database. We will set tasks to be automatically done every minute. You can write your own logic in the command. I will also show you how to set up a cron job on the server with Laravel 11. So let's follow the steps below to do this example.

laravel 11 cron job example

Step for Laravel 11 Cron Job Task Scheduling Example

  • Step 1: Install Laravel 11
  • 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:

Install Laravel 11

This step is not required; 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. The custom command will execute with task scheduling using cron job. So, let's run the below command to create a 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()
    {
        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 in the console.php file with the time when you want to run your command, as shown in the following 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

routes/console.php

<?php
  
use Illuminate\Support\Facades\Schedule;
  
Schedule::command('demo:cron')->everyMinute();

Step 4: Run Scheduler Command For Test

Now we are ready to run our cron, so you can manually check using the following command of your cron. So let's run the below command:

php artisan schedule:run

After running the above command, you can check the log file where we already printed some text. So open your log file; it looks like below:

storage/logs/laravel.php

[2024-03-29 03:51:02] local.INFO: Cron Job running at 2024-03-29 03:51:02  
[2024-03-29 03:52:01] local.INFO: Cron Job running at 2024-03-29 03:52:01  
[2024-03-29 03:53:02] local.INFO: Cron Job running at 2024-03-29 03:53:02  

Laravel 11 Cron Job Setup on Server

Here, I will show you how to set up a cron job command on the server. You need to install crontab on the server. If you are using Ubuntu Server, then it is already installed. So let's run the below command and add a new entry for the cron job.

crontab -e

Now, add the following line to the crontab file. Make sure you set your project path correctly within it.


* * * * * cd /path-to-your-project & php artisan schedule:run >> /dev/null 2>&1

Now, you can check on server as well.

Output:

I hope it can help you...

Shares