How to create cron job scheduler in Laravel 5

Published Date: 05-May-2018 | Tags: Laravel 5.5  Cron Job  

This tutorial I want to show you how to create job scheduler with cron in laravel 5.

The easiest and fastest way to do is to edit file \App\Console\Kernel.php and write your code in schedule() function.

Please see the example below.

<?php

namespace App\Console;

use App\Customer;
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 = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
//      This code means that it will automatically add to customer table everyday at 00:00 (mid night)
        $schedule->call(function () {
            $customer = new Customer();
            $customer->name = 'Customer Name';
            $customer->gender = 'Male';
            $customer->email = 'customer@email.com';
            $customer->save();
        })->dailyAt('00:00');
    }

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

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

Then go to terminal and run this command.

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

Note: PROJECT_ROOT is the path of your project directory.

Hope you can do it.



© 2018 All Rights Reserved.