Laravel9 CRON scheduling
Tags: cron, laravel
Published: 2022-11-02 05:51:33

Below example is of checking Order Status from Shiprocket and updating it in the database hourly. 

Execute the below command:
`
php artisan make:command OrderStatusCheck--command=orderstatuscheck:cron
`

Kernel.php in App\Console
```php
<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
    // 

    /**
     * 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('orderstatuscheck:cron')->hourly()->withoutOverlapping();
        // $schedule->command('inspire')->hourly()->withoutOverlapping();
    }

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

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

OrderStatusCheck.php
```php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Order;
use App\Models\OrderShiprocket;
use App\Traits\GeneralTrait;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Exception\GuzzleException;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Checking Order status';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info('OrderStatusCheck CRON Iteration Started , DATE: '.date("Y-m-d h:i:s"));
        $orders = Order::whereIn('order_status', ['shipment_pickup_scheduled', 'awb_generated'])->with('orderShiprocket')->get();
        foreach($orders as $order)
        {
            $thisToken = GeneralTrait::generateShipRocketToken();
            $client = new \GuzzleHttp\Client();

            try{

                $prod_st_pck = [];//For excluding products in Store pickup
                if($order->store_pickup == 1 && $order->store_prickup_arr != null)
                    $prod_st_pck = array_keys((array)json_decode($order->store_prickup_arr));

                foreach($order->orderShiprocket as $shipment)
                {
                    if(!in_array($shipment->product_id, $prod_st_pck)) //If not in store pickup array
                    {
                        $g_request = $client->requestAsync('POST', 'https://apiv2.shiprocket.in/v1/external/courier/track/awbs',[
                            "headers"=>[
                                'Content-Type' => 'application/json',
                                "Authorization"=>"Bearer ".$thisToken,
                            ],
                            'body'=>json_encode([
                                "awbs" => [$shipment->shiprocket_awb,], //The shipment id of the order you want to create the AWB for.
                            ]),
                        
                        ])->wait();              

                        if($g_request->getStatusCode() == 200)
                        {
                            $shiprocketResponse = json_decode($g_request->getBody());
                        }

                        if($shiprocketResponse != null)
                        {
                            if(current($shiprocketResponse) == false) //array el 0 returns false
                            {
                                Log::info('OrderStatusCheck CRON shiprocketResponse response false, DATE: '.date("Y-m-d h:i:s"));
                                //return response()->json(['status'=>'Shipment not picked up or Shipment has not been scheduled for pickup'], 400);
                            }
                            elseif(current($shiprocketResponse) != false)//If successfully getting a shipment pickup response
                            {
                                $order = OrderShiprocket::where('shiprocket_awb', $shipment->shiprocket_awb)->first();
                                $order->update([
                                    'shiprocket_status' => current(current($shiprocketResponse)->tracking_data->shipment_track)->current_status,
                                    'edd' => current(current($shiprocketResponse)->tracking_data->shipment_track)->edd,
                                    'track_url' => current($shiprocketResponse)->tracking_data->track_url,  //For saving Track URL
                                ]);
                            }
                        }
                        if($shiprocketResponse == null)
                        {
                            Log::info('OrderStatusCheck CRON shiprocketResponse response null, DATE: '.date("Y-m-d h:i:s"));
                            //return response()->json(['status'=>'No response recieved from Shiprocket, must be issue with AWB'], 400);
                        }
                        // Log::info('OrderStatusCheck CRON Iterating , DATE: '.date("Y-m-d h:i:s"));
                    }
                }
            }
            catch (GuzzleException  $e1) {
                Log::info('OrderStatusCheck CRON GuzzleException, DATE: '.date("Y-m-d h:i:s").' '.$e1->getMessage());
            }  
            Log::info('OrderStatusCheck CRON Iteration Completed, DATE: '.date("Y-m-d h:i:s"));
        }
        
        // Log::info('OrderStatusCheck CRON running , DATE: '.date("Y-m-d h:i:s"));
        // return 0;
    }
}

```

For starting CRON on Server:
```
php artisan schedule:run

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