0

I am trying to schedule a cron job for importing csv files which consists of the product details. But the cron is not working. can anyone help me resolving this issue?

I am using the following code in crontab.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="cron_csv" instance="Cron\Csv\Cron\Test" method="myCronFunction">
<schedule>* * * * *</schedule>
</job>
</group>
</config>

And this is my cron fuction :

public function myCronFunction()
{
    $file = fopen('var/import/test123.csv', 'r', '"'); // set path to the CSV file
if ($file !== false) {

require __DIR__ . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');

// used for updating product stock - and it's important that it's inside the while loop
$stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');

// add logging capability
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/import-new.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$header = fgetcsv($file); // get data headers and skip 1st row

// enter the min number of data fields you require that the new product will have (only if you want to standardize the import)
$required_data_fields = 3;

while ( $row = fgetcsv($file, 3000, ",") ) {

    $data_count = count($row);
    if ($data_count < 1) {
        continue;
    }

    // used for setting the new product data
    $product = $objectManager->create('Magento\Catalog\Model\Product');         
    $data = array();
    $data = array_combine($header, $row);

    $sku = $data['sku'];
    if ($data_count < $required_data_fields) {
        $logger->info("Skipping product sku " . $sku . ", not all required fields are present to create the product.");
        continue;
    }

    $name = $data['name'];
    $description = $data['description'];
    $shortDescription = $data['short_description'];
    $qty = trim($data['qty']);
    $price = trim($data['price']);

    try {
        $product->setTypeId('simple') // type of product you're importing
                ->setStatus(1) // 1 = enabled
                ->setAttributeSetId(4) // In Magento 2.2 attribute set id 4 is the Default attribute set (this may vary in other versions)
                ->setName($name)
                ->setSku($sku)
                ->setPrice($price)
                ->setTaxClassId(0) // 0 = None
                ->setCategoryIds(array(2, 3)) // array of category IDs, 2 = Default Category
                ->setDescription($description)
                ->setShortDescription($shortDescription)
                ->setUrlKey($url_key) // you don't need to set it, because Magento does this by default, but you can if you need to
                ->setWebsiteIds(array(1)) // Default Website ID
                ->setStoreId(0) // Default store ID
                ->setVisibility(4) // 4 = Catalog & Search
                ->save();

    } catch (\Exception $e) {
        $logger->info('Error importing product sku: '.$sku.'. '.$e->getMessage());
        continue;
    }

    try {
        $stockItem = $stockRegistry->getStockItemBySku($sku);

        if ($stockItem->getQty() != $qty) {
            $stockItem->setQty($qty);
            if ($qty > 0) {
                $stockItem->setIsInStock(1);
            }
            $stockRegistry->updateStockItemBySku($sku, $stockItem);
        }
    } catch (\Exception $e) {
        $logger->info('Error importing stock for product sku: '.$sku.'. '.$e->getMessage());
        continue;
    }
    unset($product);
}
fclose($file);
}
}
3
  • Try this : php bin/magento cron:run command if it is working then you need to check your server CRON configuration.
    – kunj
    May 25, 2018 at 4:46
  • When I run the cron:run it is showing Ran jobs by schedule. But the import is not happening. Products are not added to the catalog.
    – Vignesh S
    May 25, 2018 at 4:52
  • Check whether entry is happening in Cron table if not it is problem with cron May 25, 2018 at 4:58

0

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.

Browse other questions tagged or ask your own question.