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="AbcAbandonObserverAbandon" method="execute">
<schedule>* * * * *</schedule>
</job>
</group>
</config>
Observer file
Abandon.php
class Abandon implements ObserverInterface
{
protected $_objectManager;
/**
* @param MagentoFrameworkObjectManagerInterface $objectManager
*/
public function __construct(
MagentoFrameworkObjectManagerInterface $objectManager
) {
$this->_objectManager = $objectManager;
}
public function execute(MagentoFrameworkEventObserver $observer)
{
$writer = new ZendLogWriterStream(BP . '/var/log/abondoncronrunobserver.log');
$logger = new ZendLogLogger();
$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 ABCAbandonCron;
use PsrLogLoggerInterface;
class Run {
protected $logger;
protected $scopeConfig;
public function __construct(
LoggerInterface $logger,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
){
$this->logger = $logger;
$this->scopeConfig = $scopeConfig;
}
public function execute(){
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$cartObj = $objectManager->get('MagentoCheckoutModelCart');
$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