1

I want to run an observer function through a Cron job. Can anyone share the simple observer function.?

Here is my code

<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="abandon_cron_test" instance="Abc\Abandon\Observer\Abandon" method="execute">
               <schedule>* * * * *</schedule>
         </job>
     </group>
</config>

Observer file

Abandon.php

class Abandon implements ObserverInterface
{

    protected $_objectManager;

    /**
    * @param \Magento\Framework\ObjectManagerInterface $objectManager
    */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_objectManager = $objectManager;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/abondoncronrunobserver.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info('cron successfully');
    }
}

NO, there is no hard requirement to run the observer in cron. Here am using cron/run.php file to use in cronjob. But am not getting quote data in this file.

Here is my code:

  namespace ABC\Abandon\Cron;

    use \Psr\Log\LoggerInterface;
    class Run {

    protected $logger;
    protected $scopeConfig;
    public function __construct(
    LoggerInterface $logger,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ){
    $this->logger = $logger;
    $this->scopeConfig = $scopeConfig;

    }


    public function execute(){

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cartObj = $objectManager->get('\Magento\Checkout\Model\Cart'); 
    $quoteId = $cartObj->getQuote()->getId();
    $itemsArray = $cartObj->getQuote()->getAllItems();
    foreach($itemsArray as $item) {
    $productName[] = $item->getName();
    }
    if(is_array($productName)){
    $productNames .= implode(';',$productName);
    }
    $abdata['productNames'] = $productNames;
    $abdata['quoteid'] = $quoteId;
    return $abdata;
    }

    }

Thanks

7
  • 1
    You cannot run an observer on cronjob
    – Amit Bera
    Commented Apr 11, 2019 at 10:10
  • The observer need a parameter an how you will get that parameter
    – Amit Bera
    Commented Apr 11, 2019 at 10:11
  • Also, I am running cron/run.php through cron but In this file I can't get the quote data for the cron job in cron/run.php. How I can do?
    – Shomita
    Commented Apr 11, 2019 at 10:13
  • why you want to run cron with observer? Commented Apr 11, 2019 at 10:15
  • @Shiwani check this answer Commented Apr 11, 2019 at 10:25

1 Answer 1

0

Try with below code:

In this case, we could not get current customer quote from cron, from below code you will get all items productnames and quoteid in array you will need to get quote_id of customer and add in to filter:

ABC/Abandon/etc/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="custom_cronjob" instance="ABC\Abandon\Cron\Check" method="execute">
        <schedule>*/1 * * * *</schedule>
    </job>
</group>
</config>

ABC/Abandon/Cron/Check.php

<?php 
namespace Wagento\Australiapost\Cron;

class Check {

    /**
     * @var \Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory
     */
    protected $itemCollectionFactory;

    /**
     * @var \Magento\Quote\Model\QuoteRepository
     */
    protected $quoteRepository;

    /**
     * @var \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory
     */
    protected $quoteCollectionFactory;

    public function __construct(
        \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteCollectionFactory,
        \Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory $itemCollectionFactory,  
        \Magento\Quote\Model\QuoteRepository $quoteRepository 
    ) {

        $this->quoteCollectionFactory = $quoteCollectionFactory;
        $this->quoteRepository = $quoteRepository;
        $this->itemCollectionFactory = $itemCollectionFactory;
    }
    public function execute()
    {

        $abdata = [];
        $productNames = $quoteId = '';
        $itemCollection =$this->itemCollectionFactory->create();

        // You can also filter the collection with below code
        /* 
        $itemCollection =$this->itemCollectionFactory->create()
        ->addFieldToSelect('created_at')
        ->addFieldToSelect('item_id')
        ->addFieldToSelect('quote_id')
        ->addFieldToFilter('quote_id', ['eq' => $quoteID]);    */ 

        if (count($itemCollection)) {
            foreach ($itemCollection as $item)
            {
                $productName[] = $item->getName();
                $quoteIds[] = $item->getQuoteId();
            }
            if(!empty($productName)){
                $productNames .= implode(';',$productName);
            }
            if(!empty($quoteIds)){
                $quoteId .= implode(';',$quoteIds);
            }
            $abdata['productNames'] = $productNames;
            $abdata['quoteid'] = $quoteId;
        }
        return $abdata;
    }
}
8
  • Thanks for the reply. I am getting all the quote ids. But I need to get current quote id of the logged in account For instance: [email protected] -- I want to get this email id's abandon products and quote id.
    – Shomita
    Commented Apr 11, 2019 at 11:39
  • In cron you will not get current user session, you will get all the quote items. based on you need you will need to filter the collection. Commented Apr 11, 2019 at 11:41
  • How I can filter ?
    – Shomita
    Commented Apr 11, 2019 at 11:43
  • $itemCollection =$this->itemCollectionFactory->create()->addAttributeToSelect('*')->addFieldToFilter('quote_id', ['eq' => $quoteIDYouNeedToFilter]); Commented Apr 11, 2019 at 11:45
  • Need to get current login quote data(abandon cart data) of logged in User.
    – Shomita
    Commented Apr 11, 2019 at 12:12

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.