6

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?

  • I'm still finding this question very intriguing. I'm currently running into this problem with a multi-website installation with different timezones per website. Having one cron job scheduled differently per website seems like the need, but isn't possible since the crons only run based on the default websites timezone/locale. Did you do anything more on this topic or have any more insights? – floorz Oct 31 '19 at 19:53
5
+50

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"}

| improve this answer | |
0

Generally cron job runs globally.

In the script you can manage your customization on Website/Store/Store View Level.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.