Search code examples
laravellaravel-5.8cron-task

Cron run schedule not running automatically on the server


I have this cron job code in Laravel-5.8 application:

App/Console/Commands:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Hr\HrDesignation;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Exception;
use Notification;
use GuzzleHttp\Client; 
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;


class UpdateCreateDesignation extends Command
{
    protected $signature = 'updatecreatedesignations';

    protected $description = 'Update or Create Designation';

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

    public function handle()
    {
        $client = new Client();
        $res = $client->request('GET','https://api.cloudjkk.net/jkkapp/profile/all-designations', [
        'query' => ['key' => 'dddddd']
    ])->getBody();

        $clientdatas = json_decode($res->getContents(), true);    
        
        foreach($clientdatas as $clientdata)
        {        
              if ($clientdata['job_title']) {
            $designation = HrDesignation::updateOrCreate([
                'designation_name' => $clientdata['job_title']
            ],
            [
                'description'       => $clientdata['job_description'],
                'company_id'        => 1,          
            ]); 
        }
        }

    } 
}

For the schedule, I have this code in the kernel which is supposed to run by 1:00a.m. every day

kernel.php

<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{

    protected $commands = [
        'App\Console\Commands\UpdateCreateDesignation',
    ];

    protected function schedule(Schedule $schedule)
    {       
        $schedule->command('updatecreatedesignations')
                ->dailyAt('01:00'); 
                                                                                                     
    }

    protected function commands()
    {

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

I observe that the cron job is not running on the server as scheduled by 01:00.

There is no error.

How do I resolve this?

Thanks


Solution

  • Laravel needs to run the php artisan schedule:run every minute. If the current time is 01:00, that task is executed.

    So you need to:

    • Add a cronjob every minute * * * * *.
    • Go to the directory cd /path-to-your-project
    • Run the artisan command that will match the time php artisan schedule:run

    You can test this if you add a job with ->everyMinute();

    $schedule->command('increment-db-int')
        ->everyMinute();