Session is not working in cron file

by Ramesh KR   Last Updated January 09, 2018 13:09 PM

namespace send\sms\Cron; 

use Magento\Framework\ObjectManagerInterface;

class Run  /*extends send\sms\Controller\Customr*/  {

   public function execute()
   {

    $om = \Magento\Framework\App\ObjectManager::getInstance();
     $customerSession = $om->get('Magento\Customer\Model\Session');
     if($customerSession->isLoggedIn()) {

         $idd =$customerSession->getCustomer()->getId();

     }
       $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');  
    $connection= $this->_resources->getConnection();
    //$sql = "UPDATE `total_cashback` SET is_active= 100 WHERE user_id = '801' ";  
     $sql = "UPDATE `wallet_discounts` SET is_active = 12000 WHERE customer_id = $idd ";  
    $connection->query($sql);
   }



}

Cannot get customer Id in the above snippet.



Answers 1


You can not access customer session in cron (not impossible, but very hard to do). You could try creating an observer for customer_login and add your custom logic there.

To create an observer for customer_login

in app/code/Send/Sms/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_login">
        <observer name="send_sms_customer_login" instance="Send\Sms\Observer\Frontend\CustomerLoginObserver"/>
    </event>
</config>

In Send\Sms\Observer\Frontend\CustomerLoginObserver.php

<?php
namespace Send\Sms\Observer\Frontend;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;


class CustomerLoginObserver implements ObserverInterface
{

     * @param EventObserver $observer
     * @return void
     */
    public function execute(EventObserver $observer)
    {
        $customerId = $observer->getCustomer()->getId()
        //custom logic here
    }
}

If you want to go the cron route, you could take a look at how Magento implement the "Customers Now Online" feature in Admin -> Customers -> Now Online.

Renon Stewart
Renon Stewart
January 09, 2018 13:49 PM

Related Questions


How to get Customer Id in Cron job function?

Updated January 09, 2018 09:09 AM


Cron job permission issue?

Updated January 28, 2018 17:09 PM

How can i setup CRON JOB In wamp Windows?

Updated April 18, 2018 07:09 AM

Reset overlay button (cronjobs)

Updated December 22, 2017 21:09 PM