简体   繁体   中英

How to setup cron dynamically via admin in magento 2 (custom module)

如何在Magento 2中的config.xml(自定义模块)中动态设置cron

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="YourVenDoerName\CustomModule\Cron\Test" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Cheers

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(
    \Magento\Framework\App\Config\ConfigResource\ConfigInterface  $resourceConfig)
{
    $this->resourceConfig = $resourceConfig;
}        

public function execute()
{
    $newvalue = $dynamicvalue;

    $this->resourceConfig->saveConfig(
        'section/group/field', 
        $newvalue, 
        \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 
        \Magento\Store\Model\Store::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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM