1

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



        }
}
4
  • have you configured cron on server?
    – kunj
    Jun 4, 2018 at 6:19
  • I don't know this step, Can u Please guide me. @kunj Jun 4, 2018 at 6:20
  • I have added answer.
    – kunj
    Jun 4, 2018 at 6:23
  • @JBPakalapati You define instance="Autosynch\synchProduct\Page\Service" but you create Service file in wrong place: "Autosynch\synchProduct\Controller\Page\Service" So your cron job can not run. Oct 29, 2020 at 2:11

2 Answers 2

0

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.

8
  • I used this command then php bin/magento cron:run I got result as shown in screenshot in question, it creates now corn jobs but these are in pending state for very long time. what should i do now. Jun 4, 2018 at 6:26
  • first time it will create cron schedule second time while you run this command it will run your schedule crons.
    – kunj
    Jun 4, 2018 at 6:28
  • Even you get out put like error by php bin/magento cron:run this command
    – kunj
    Jun 4, 2018 at 6:28
  • I got this Result when i used that corn:run command : C:\xampp\htdocs\Magento-CE>php bin/magento cron:run Failed loading c:\xampp\php\ext\xdebug.dll PHP Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_interbase.dll' - The specified module could not be found. in Unknown on line 0 Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_interbase.dll' - The specified module could not be found. in Unknown on line 0 Ran jobs by schedule. Jun 4, 2018 at 6:31
  • you have to enable or install php_interbase.dll .
    – kunj
    Jun 4, 2018 at 7:52
0

Create the cron job

To create a cron job for the Magento file system owner, enter the following command as a user with root privileges:

crontab -u <Magento file system owner user name> -e

For example,

crontab -u magento_user -e

A text editor displays. (You might need to choose a text editor first.)

\* * * * * <path to php binary> <magento install dir>/bin/magento cron:run | grep -v "Ran jobs by schedule" >> <magento install dir>/var/log/magento.cron.log

\* * * * * <path to php binary> <magento install dir>/update/cron.php >> <magento install dir>/var/log/update.cron.log

\* * * * * <path to php binary> <magento install dir>/bin/magento setup:cron:run >> <magento install dir>/var/log/setup.cron.log

where

<path to php binary> is the absolute file system path to your PHP binary <magento install dir> is the directory in which you installed the Magento software; for example, /var/www

| grep -v "Ran jobs by schedule"

Reference

3
  • I tried this is the result i got : C:\xampp\htdocs\Magento-CE>crontab -u superadmin -e 'crontab' is not recognized as an internal or external command, operable program or batch file. Jun 4, 2018 at 6:29
  • crontab is not for windows OS
    – kunj
    Jun 4, 2018 at 6:29
  • So, you have to run cron by command.
    – kunj
    Jun 4, 2018 at 6:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.