Laravel 9 Cron Job Task Schedule Tutorial

Reading Time: 8 minutes
3,321 Views

Now a days, Adding Background process is common to applications. Background process is termed as Cron jobs of any application.

Few examples of background processes like for sending an email to all subscribed users, running database queries to take backups etc. There are lots of example you will find in daily life which handle by application’s back face.

Cron jobs needs to specified with trigger time. Here trigger time means when it has to start it’s execution. It can be like every minute, every hour, a day etc. Inside this article we will see the concept of Laravel 9 Cron Job Task Schedule.

This tutorial is going to be quite interesting to learn and see the concept of Cron job task scheduler methods and step by step procedure in laravel.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Step #1: Create New Command

In the very first step of this Cron scheduling task, we are going to create a Laravel custom command. This custom command will help us to run our background tasks.

So, to create custom command we have an artisan command.

$ php artisan make:command TestCron --command=test:cron

When we run this command, it will create a Commands folder inside /app/Console if it doesn’t exists.

Inside this folder we will have a file with the name TestCron.php inside /app/Console/Commands folder.

Step #2: Command Settings

When you open TestCron.php file, you will find few protected variables.

protected $signature = 'test:cron';

protected $description = 'This is a sample cron to log message';

In this file, most important method is handle(). This method runs when cron triggers.

Here, we have the complete code. Write this code into TestCron.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
//use App\Models\Student;

class TestCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This is a sample cron to log message';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Simple Cron to log message
        Log::info("Successfully, cron is running");

        // Also we can database stuff here

        // Student::create([
        //     "name" => "Sample",
        //     "email" => "sample@gmail.com",
        //     "mobile" => "8529630147"
        // ]);

        //return 0;
    }
}

Inside this handle() method, you can add any type of your job task as Sending an email, Data insert into database, taking data dumps etc.

Next,

Back to terminal and see cron command inside artisan command panel.

Let’s schedule this cron to task scheduler.

Step #3: Register Command as Task Scheduler

Next,

To register Cron jobs go to /app/Console folder and find a file called Kernel.php inside it. We need to register our created cron command here with any time when we want to trigger.

Here, are the list of trigger time (scheduling frequencies) available for task scheduling.

Here is the updated code of Kernel.php file.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\TestCron::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('test:cron')
                 ->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Successfully, we have registered Cron command to Kernel.php

Step #4: Test Job Scheduling Task

Open terminal and type this command

$ php artisan schedule:run

When it executes the command will log message into the log file.

Log file laravel.log you will find inside /storage/logs/ folder. Inside this file cron will add the statement i.e “Successfully, cron is running“.

Now let’s set it as on permanent basis by using crontab console command.

Step #5: Settings Cron Task inside Crontab

Open terminal and type the command

$ crontab -l

This command will list all crons that you have added.

Now, To add new cron tasks, again back to terminal and type the command

$ crontab -e

It will open an interface to your terminal to register or add new tasks. So let’s add

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
  • * * * * * Trigger Time, It indicates our task will run every minute
  • /path-to-your-project This is path of laravel application project
  • php artisan schedule:run Command to run.

We hope this article helped you to learn about Laravel 9 Cron Job Task Schedule Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.