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