Magento – Magento 2: Scope for cron jobs

cronmagento2scope

In which scope does Magento 2 run cron jobs?

If I have a multi-site system, does the framework invoke my job once for the entire system, or does it repeat the job for each store?

The doc says they run in store view scope, however, my practical experiments show only one invocation.

If they indeed run in store view scope, then how do I identify the site/store scope for which it runs?

Best Answer

Cron runs under console and system (server) doesn't know which store you are requested like on frontend.

I do not think you need to care about scope in crontab. System runs cron jobs in crontab area and if you need to change something for the store you need to create new cron job, load this store and change it.

Actually you can simply check this..

Vendor/Module/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_job" instance="Vendor\Module\Cron\Custom" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Vendor/Module/Cron/Custom.php

namespace Vendor\Module\Cron;

class Custom
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;
    
    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->storeManager = $storeManager;
        $this->logger = $logger;
    }

    /**
     * @return void
     */
    public function execute()
    {
        $this->logger->info('Store Info',  $this->storeManager->getStore()->toArray());
    }
}

Run in console:

php bin/magento setup:cron:run

php bin/magento cron:run

Here is result:

main.INFO: Store Info {"store_id":"0","code":"admin","website_id":"0","group_id":"0","name":"Admin","sort_order":"0","is_active":"1"}

Related Topic