Laravel 8 – How to Setup Cron Job Task Scheduling Tutorial

Cron jobs play a crucial role in automating repetitive tasks in web applications. Laravel offers an elegant way to schedule and manage cron jobs with its built-in task scheduler. In this tutorial, we’ll go through the process of setting up a cron job in Laravel, step by step. We will create a simple example to…

By.

min read

Cron jobs play a crucial role in automating repetitive tasks in web applications. Laravel offers an elegant way to schedule and manage cron jobs with its built-in task scheduler. In this tutorial, we’ll go through the process of setting up a cron job in Laravel, step by step. We will create a simple example to demonstrate task scheduling and execution using Laravel 8.

Cron jobs can be beneficial for various reasons, such as sending automated email notifications or updating properties and products periodically. By using Laravel’s task scheduler, you can define the frequency of the tasks, ensuring they run at the desired intervals.

 

How to Setup Cron Jobs Scheduling in Laravel?

Follow these quick steps to schedule Cron Jobs in Laravel:

Step 1 – Install Laravel Application
Step 2 – Create a New Command
Step 3 – Register the Command in Task Scheduler
Step 4 Test the Scheduler Command

 

Step 1: Install Laravel Application

If you don’t have a Laravel application set up, you need to create one first. Run the following command to get a fresh Laravel application:

composer create-project --prefer-dist laravel/laravel blog

 

Step 2: Create a New Command

Next, create a custom command that will be executed by the task scheduler as a cron job. Run the following command to generate a new custom command:

php artisan make:command SampleCron --command=sample:cron

 

Now, modify the command file as follows:

app/Console/Commands/SampleCron.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SampleCron extends Command
{
    protected $signature = 'sample:cron';
    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        \Log::info("Cron job is running correctly!");

        // Add your database logic here, e.g.:
        // Item::create(['name' => 'new item']);
    }
}

 

Step 3: Register the Command in Task Scheduler

Now, you need to define the command in the Kernel.php file and specify when you want it to run. Laravel provides several methods to set the frequency of tasks:

->everyMinute();
->everyFiveMinutes();
->everyTenMinutes();
->everyFifteenMinutes();
->everyThirtyMinutes();
->hourly();
->hourlyAt(17);
->daily();
->dailyAt('13:00');
->twiceDaily(1, 13);
->weekly();
->weeklyOn(1, '8:00');
->monthly();
->monthlyOn(4, '15:00');
->quarterly();
->yearly();
->timezone('America/New_York');

 

Register your custom command in the Kernel.php file:

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 $commands = [
        Commands\SampleCron::class,
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('sample:cron')
                 ->everyMinute();
    }

    protected function commands()
    {
        $this->load(DIR.'/Commands');
        require base_path('routes/console.php');
    }
}

 

Step 4: Test the Scheduler Command

Your cron job is now ready to run. You can manually test it by executing the following command:

php artisan schedule:run

 

After running the command, check the log file, where we have printed a message to confirm the cron job’s execution:

storage/logs/laravel.log

[2023-01-18 08:36:42] local.INFO: Cron job is running correctly!
[2023-01-18 08:36:52] local.INFO: Cron job is running correctly!
[2023-01-18 08:36:55] local.INFO: Cron job is running correctly!

 

Lastly, add a single entry to your server’s crontab file to manage the scheduled task:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

Or

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

 

Frequently Asked Questions

 

What is a cron job in Laravel?

A cron job in Laravel is a scheduled task that runs automatically at specific intervals, such as sending email notifications or updating records.

 

How do I create a cron job in Laravel?

In Laravel, you can create a cron job by defining a custom command, registering the command in the task scheduler, and setting the desired frequency for the task.

 

How can I test a Laravel cron job?

You can test a Laravel  cron job by running the php artisan schedule:run command and check the log file for the expected output.

 

What are the benefits of using Laravel’s task scheduler for cron jobs? Using Laravel’s task scheduler allows you to manage cron jobs more efficiently by defining the frequency, handling dependencies, and utilizing Laravel’s built-in functionality.

 

Can I run multiple cron jobs in Laravel? Yes, you can run multiple cron jobs in Laravel by creating multiple custom commands and registering them in the task scheduler with the desired frequency.

 

Conclusion

In this tutorial, we covered the process of setting up a cron job in Laravel using its built-in task scheduler. By following these steps, you can create, register, and manage cron jobs in Laravel effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *