Magento Cron in Backend Configuration

The way to make that cron_expr a setting in the backend that can be changed

Posted on April 4, 2016 in Magento

We know how to setup a cron using the config.xml crontab:


<crontab>
    <jobs>
        <company_export_send_all>
            <schedule>
                <cron_expr>* * * * *</cron_expr>
            </schedule>
            <run>
                <company_export/observer::exportOrderData</company_export>
            </run>
        </company_export_send_all>
    </jobs>
</crontab>

But what if we want to set up cron_expr value in the backend like other system configuration. The solution is simple. It involves some xml files. (config.xml and system.xml). config.xml:


#config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Company_Export>
            <version>0.1.0</version>
        </Company_Export>
    </modules>
    <global>
        <models>
            <company_export>
                <class>Company_Export_Model</class>
            </company_export>
        </models>
    </global>
    <default>
        <export>
            <order>
                 <cron_settings>*/5 * * * *</cron_settings>
            </order>
        </export>
    </default>
    <crontab>
        <jobs>
            <company_export_send_order>
                <schedule>
                     <config_path>export/order/cron_settings</config_path>
                </schedule>
                <run>
                     <model>company_export/observer::exportOrderData</model>
                </run>
            </company_export_send_order>
        </jobs>
    </crontab>
</config>

system.xml:


<?xml version="1.0"?>
<config>
    <tabs>
        <feedsconfig translate="label" module="export">
            <label>Feeds Configuration</label>
            <sort_order>9999</sort_order>
        </feedsconfig>
    </tabs>
    <sections>
        <export translate="label" module="export">
              <label>Export</label>
              <tab>feedsconfig</tab>
              <frontend_type>text</frontend_type>
              <sort_order>1000</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>1</show_in_store>
              <fields>
                   <cron_settings>
                        <label>How often do you want  the cron to run?</label>
                        <frontend_type>text</frontend_type>
                        <sort_order>40</sort_order>
                        <comment>use Crontab Format (Eg. "*/5 * * * *" for every 5 minutes)</comment>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                   </cron_settings>
              </fields>
        </export>
    </sections>
</config>

I hope this tutorial will help you in the future project.


comments powered by Disqus