0

How to create a cron job for out of stock that must daily run and check how many products are out of stock

1 Answer 1

0

Create the file app/code/Custom/Module/etc/crontab.xml with the following content:

<?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_module_out_of_stock_check" instance="Custom\Module\Cron\OutOfStockCheck" method="execute">
            <schedule>0 0 * * *</schedule>
        </job>
    </group>
</config>

This configuration schedules the cron job to run every day at midnight (00:00).

Create the PHP class for the cron job.

Create the file app/code/Custom/Module/Cron/OutOfStockCheck.php with the following content:

<?php
namespace Custom\Module\Cron;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\ObjectManager;
use Psr\Log\LoggerInterface;

class OutOfStockCheck
{
    /**
     * @var CollectionFactory
     */
    private $productCollectionFactory;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        CollectionFactory $productCollectionFactory,
        LoggerInterface $logger
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->logger = $logger;
    }

    public function execute()
    {
        $outOfStockProductsCount = $this->getOutOfStockProductsCount();
        $this->logger->info("Total out of stock products: " . $outOfStockProductsCount);
    }

    private function getOutOfStockProductsCount()
    {
        try {
            $collection = $this->productCollectionFactory->create();
            $collection->addFieldToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
            $collection->addFieldToFilter('quantity_and_stock_status', ['eq' => 0]);

            return $collection->getSize();
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
            return 0;
        }
    }
}

Let me know if any queries.

Thanks

Your Answer

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

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