skip to Main Content

How can I setup cron dynamically in config.xml (custom module) in Magento 2?

2

Answers


  1. Magento2 has a different scheme to merge layout config so you have to create a new file that called crontab.xml under your_custom_module/etc folder. And then you can add your cron config like this one:

    <?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_cronjob" instance="YourVenDoerNameCustomModuleCronTest" method="execute">
                <schedule>* * * * *</schedule>
            </job>
        </group>
    </config>
    
    Login or Signup to reply.
  2. I will try to make a proposition, not sure if it completely answers your question tho.

    So config.xml is setting a default value for your configuration field set in system.xml

    So you can have another cron job that runs every minute (* * * * *) and dynamically change this value set in system.xml. Something like this:

    public function __construct(
        MagentoFrameworkAppConfigConfigResourceConfigInterface  $resourceConfig)
    {
        $this->resourceConfig = $resourceConfig;
    }        
    
    public function execute()
    {
        $newvalue = $dynamicvalue;
    
        $this->resourceConfig->saveConfig(
            'section/group/field', 
            $newvalue, 
            MagentoFrameworkAppConfigScopeConfigInterface::SCOPE_TYPE_DEFAULT, 
            MagentoStoreModelStore::DEFAULT_STORE_ID
        );
    
    }   
    

    So basically two cron jobs.
    One that actually does the job you want and one that tweaks it schedule.
    Also you can tweak the schedule of it dynamically in an observer, plugin or some other class depending on your needs using the code above.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search