Magento – Magento2: CRON Job is scheduled but Not Running

controllerscronmagento2

I have created a Cron job followed this question Installed the Extension and check it from admin back it says the job is pending. Below is the screenshot and my code in detail, Please let me know if I am doing wrong anywhere.

enter image description here

All jobs are in a pending state for a very long time.

app\code\Autosynch\synchProduct\etc\corntab.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="custom_AutoSynch_cronjob" instance="Autosynch\synchProduct\Page\Service" method="execute">
            <schedule>10 * * * *</schedule>
        </job>
    </group>
</config>

I need to run this below Code.

app\code\Autosynch\synchProduct\Controller\Page\Service.php

<?php
namespace Autosynch\synchProduct\Controller\Page;
use Magento\Framework\HTTP\Client\Curl;

class Service extends \Magento\Framework\App\Action\Action {
        /**
        * @param \Magento\Framework\App\Action\Context $context
        * @param \Magento\Framework\HTTP\Client\Curl $curl
        */
        protected $_curl;

        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            Curl $curl
        ) 
        {

            parent::__construct($context);
            $this->_curl =$curl;
        }
         /**
         * Send SMS
         * @param type $mobile_no
         * @param type $body
         */
        public function getMyCurlResponse($url)
        {
          //$url = urlencode($url);  
          $this->_curl->get($url);
          $response = $this->_curl->getBody();

         return $response;
        }

        public function myPostCallResponse(){
            $ch = curl_init();
            $url = "http://api.geonames.org/citiesJSON";
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_POST, 1); 
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, "north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=jb1234");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $data = curl_exec($ch);
            $resultArray = json_decode($data)->geonames;



            //print_r($data);

            foreach ($resultArray as $key => $value) {
                # code...
                echo " City : ".$value->toponymName.", \n";
            }

            die();
        }

        public function execute()
        {
            //$priceCheck = 'http://alaincopheadofficen-2.fortiddns.com:555/webservices/getupdates.php';

            $priceCheck = 'http://alaincopheadofficen-2.fortiddns.com:555/webservices/getupdates.php';


             $result = $this->getMyCurlResponse($priceCheck);

             $resArray = json_decode($result)->result;

             foreach ($resArray as $key => $value) {
                 # code...
                //echo " SKU: ",$value->sku,", name: ",$value->name,", Price: ",$value->price, ", Qty: ",$value->qty,". \n";

                $product_id = $value->sku; 
                $price = $value->price;
                $qty = $value->qty;
                 echo " \n\n in check for update Method SKU: ", $product_id,", Price: ", $price, ", Qty: ",$qty;
                 $this->updateProduct($product_id, $price, $qty);
             }

        }

        public function updateProduct($product_id, $price, $qty1){

 // echo "in Update Product",$product_id,", price : ",$price, ", Qty : ",$qty1,"";
       ini_set('max_execution_time', 0);
       $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
       $objectManager = $bootstrap->getObjectManager();
       $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
       $state = $objectManager->get('\Magento\Framework\App\State');
       $state->setAreaCode('frontend');
       $storeId = '1'; //Store ID
       //$product = $objectManager->get('catalog/product');


       $productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
        //$product = $productFactory->create()->setStoreId($storeId)->load($product_id);
       $product = $productFactory->create();
       $prduct_id_sku = $product->load($product->getIdBySku($product_id));
       //echo "in Update Product method : ", pro;

       $oldprice = $product->getPrice();
       $productName = $product->getName();

      // echo "Product Name:", $productName, ",\n Product ID:",$product->getId(),", SKU: ",$prduct_id_sku->getSku()," ";

    //   echo ",\n product Quantity: ",$prduct_id_sku->getStockItem();

            // $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
            // echo $stock->getQty();
               $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');

               $oldstock = $StockState->getStockQty($product->getId());
         //echo $StockState->getStockQty($product->getId());//, $product->getStore()->getWebsiteId());
         //echo $StockState->getStockQty(1);
         //$StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId())
         //$product->getStore()->getWebsiteId()->suggestQty("101");
         //$Product->

         //$StockState->save();

        // echo " \n Current price is : ", $oldprice;

         if ((($oldprice != $price) || $oldstock != $qty1 ) && $oldstock) {

          $product->setPrice($price); 

         // echo ",\n new price Updated ",$price;   

          if ($oldstock != $qty1) {
            $product->setStockData(array(
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                    'qty' => $qty1 ));  
            //$product->setStockData(['qty' => $qty1, 'is_in_stock' => 1]);
        $product->setQuantityAndStockStatus(['qty' => $qty1, 'is_in_stock' => 1]);

           // echo " \n Updated Stock:";
           // print_r($product->getStockData()['qty']);
          }else{
            //echo " \n oldStock & new stock are equal ".$qty;

          }

          $product->save();


        }else {
          //echo " \n oldprice & new price are equal ".$price;       
        }


        unset($storeIds, $websiteObj, $_websiteId);
        unset($product);



        }
}

Best Answer

Try this :

You can run CRON by this command: php bin/magento cron:run by terminal or cmd. Even you can configure CRON in server by ssh using crontab -e command. Maybe you will need root user of server you can learn about Magento 2 CRON configuration from here : Magento 2 cron. You can check CRON successful run or not from cron_schedule database table. You can check CRON status by this command on the server : sudo service cron status.

Related Topic