I am working on Cron from custom module to send email from custom cron job, I created it as below but the cron job is nor working on the server.
<?php
namespace Name\Module\Cron;
use Magento\Framework\Mail\Template\TransportBuilder;
use Name\Module\Model\MyModule;
use Magento\Customer\Model\CustomerFactory;
use Name\Module\Helper\Data;
class RfqCron {
protected $_logger;
protected $customerFactory;
protected $transportBuilder;
protected $helper;
protected $_myFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Escaper $escaper,
TransportBuilder $transportBuilder,
CustomerFactory $customerFactory,
Data $helper,
\Name\Module\Model\ResourceModel\MyModule\CollectionFactory $myFactory
) {
$this->_logger = $logger;
$this->helper = $helper;
$this->_myFactory = $myFactory;
$this->customerFactory = $customerFactory;
$this->transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->_escaper = $escaper;
}
public function execute()
{
try {
$myCollection = $this->_myFactory->create();
foreach ($rmyCollection as $myData) {
$customer = $this->customerFactory->create()->load($myData->getCustomerId());
$customerInfo = array(
'name' => $customer['firstname'],
'email' => '[email protected]'
);
$currentDate = date('Y-m-d');
$myExpireDate = $myData->getExpiryDate();
if ($myExpireDate == $currentDate) {
$templateId = $this->helper->getConfigValue('mysettings/my_customer_notification/customer_email_template_expire');
$emailTemplateVariables = array(
'email' => $customerInfo['email'],
'name' => $customerInfo['name'],
'msg' => "email sent from cron"
);
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
$this->helper->sendEmailToCustomer(
$templateId, //email template id
$emailTemplateVariables, //variables
$customerInfo //receiver
);
$myData->setMyStatusId(4);
$myData->save();
}
}
$this->_logger->addDebug( "Message sent" );
return;
} catch (\Exception $e) {
$this->inlineTranslation->resume();
$this->_logger->addDebug( "Message not sent" );
return;
}
}
<?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="name_module_cron_group">
<job name="mycron" instance="Name\Module\Cron\MyCron" method="execute">
<schedule> * www-data PHP /bin/magento cron:run</schedule>
</job>
</group>
</config>