Sunday, November 17, 2024
Google search engine
HomeLanguagesLaravel 10 Cron Job Task Scheduling Example Tutorial

Laravel 10 Cron Job Task Scheduling Example Tutorial

In Laravel, a cron job refers to a scheduled task that runs automatically at specified intervals. It allows you to automate repetitive tasks in your web application, such as database backups, sending emails, generating reports, or any other task that needs to be executed periodically.

With Laravel’s built-in support for cron jobs, you can easily schedule and manage these tasks within your application. By utilizing the underlying operating system’s cron daemon, Laravel provides a convenient way to define and handle cron jobs through a concise and expressive syntax.

So, in this tutorial, you will learn how to create and use the cron job command Laravel 10 apps for task scheduling.

Laravel 10 Cron Job Task Scheduling Example Tutorial

By using the following steps, you can create and use cron job for task scheduling in laravel 10 apps:

  • Step 1: Create Cron Job Class
  • Step 2: Define the Task
  • Step 3: Configure the Schedule and Register the Task
  • Step 4: Run the Scheduler
  • Step 5: Laravel Set CronJob on the Live Server

Step 1: Create Cron Job Class

First of all, navigate to your Laravel 10 app by executing the following command on terminal:

cd /Laravel 10 app

Then execute the following command on the terminal to create LogCron job class:

php artisan make:command LogCron --command=log:cron

Step 2: Define the Task

In this step, the LogCron.php file is located in the app/Console/Commands/ directory. And add the following code to it:

<?php
   
namespace App\Console\Commands;
   
use Illuminate\Console\Command;
   
class LogCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'log:cron';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \Log::info("Cron is working fine!");
     
        /*
           Write your database logic we bellow:
           Item::create(['name'=>'hello new']);
        */
    }
}

Step 3: Configure the Schedule and Register the Task

In this step, register the above-created cron job class in the kernel.php file.

So, navigate to the app/Console directory and open Kernel.php. Then register the cron job command like the following:

<?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\LogCron::class,
    ];
     
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('log:cron')
                 ->everyMinute();
    }
     
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
     
        require base_path('routes/console.php');
    }
}

In the Kernel.php file you can schedule the task to be done when it will be the command execute(run).

You can see the following scheduler methods:

->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

Step 4: Run the Scheduler

In this step, execute the following command on the terminal to run the scheduler:

php artisan schedule:run

Step 5: Laravel Set CronJob on the live server

If you want to schedule the task on the live server use the below command :

* * * * * 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

Conclusion

By leveraging Laravel’s cron job functionality, you can streamline your application’s workflow and automate routine tasks, improving efficiency and reliability. The built-in scheduler simplifies the process of defining and managing cron jobs within your Laravel application, allowing you to focus on developing your application’s core functionality.

Whether you need to perform periodic maintenance tasks, generate reports, or trigger background processes, Laravel’s cron job support provides a flexible and powerful solution to handle these requirements seamlessly within your web application.

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Recent Comments