Cron job with parameters in magento

Today we are going to discuss about cron jobs in magento. Cron jobs can be used for a lot of stuff, like importing stock data, exporting order data, exporting affiliate feeds, importing order statuses, updating or creating product data, importing customer data, generating google site map, importing exchange rates etc etc.

As you can see there could be a lot of reasons for creating cron job for your website. Let’s start with a simple cron job by step by step implementation

Step 1 – Create a config.xml under app\code\local\Scommerce\StockImport\etc directory

<config>
    <modules>
        <Scommerce_StockImport>
            <version>0.0.1</version>
        </Scommerce_StockImport>
    </modules>
    <global>
        <models>
            <stockimport>
                <class>Scommerce_StockImport_Model</class>
            </stockimport>
        </models>
    </global>
    <crontab>
        <jobs>
            <update_stockqty> 
              <!--The above could be any unique job name-->
              <schedule><cron_expr>0 1 * * *</cron_expr></schedule> 
              <!--The above defines the frequency of the job to run-->
              <run><model>stockimport/import::updateStockQty</model></run> 
              <!--The above tells which model class function to run -->
            </update_stockqty>
        </jobs> 
    </crontab>
</config>

In the above step, we have registered a module, registered a model and defined the cron job which is going to use model for updating stock qty.

As we have defined this line stockimport/import::updateStockQty in the crontab part of the config.xml, we need to create a model class which should be Scommerce_StockImport_Model_Import  to match stockimport/import  with the function called updateStockQty.

Step 2 – Create a model class Scommerce_StockImport_Model_Import.php under app\code\local\Scommerce\StockImport\Model\Import.php with a function called updateStockQty

<?php
class Scommerce_StockImport_Model_Import extends Mage_Core_Model_Abstract
{
    protected function _construct()
    {
        parent::_construct();
        $this->_init('stockimport/import');
    }

    public function updateStockQty()
    {
        $file = "stockfile.csv"
        $data = array();
        if (file_exists($file)) {
            $parser = new Varien_File_Csv();
             $data = $parser-&gt;getData($file);            
        }
        ......
        ......
        ......
    }
}

Step 3 – Now we need to tell magento that we have a new module by creating a module file Scommerce_StockImport.xml under app\etc\modules directory with the following content -:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Scommerce_StockImport>
            <active>true</active>
            <codePool>local</codePool>
        </Scommerce_StockImport>
    </modules>
</config>

The above steps will help you schedule a stock import job which will run at 1 AM every day as we have instructed in the config.xml 0 1 * * *. Here are some more examples which you can use if you want to run your stock import more frequent or at different time -:

*/10 * * * * – Every 10 mins

*/30 * * * * – Every 30 mins

* * * * * – Every time cron job runs

0 0 * * * – Daily at midnight

0 2 * * * – Daily at 2 AM

The cron job schedule pattern is #minute# #hour# #day-of-month# #month# #day-of-week#

Last week, we had a situation where we had to update stock for multiple stores, the one and a dirty way of doing is to create another module but what if you have 30 stores, 30 modules will be a way too much to update stock! Don’t you think so?

Don’t worry we have a way around it and we always believe in writing less code and use best practices. So here we have addressed the issue. We change the above config.xml (step 1) to the following -:

<config>
    <modules>
        <Scommerce_StockImport>
            <version>0.0.1</version>
        </Scommerce_StockImport>
    </modules>
    <global>
        <models>
            <stockimport>
                <class>Scommerce_StockImport_Model</class>
            </stockimport>
        </models>
    </global>
    <crontab>
        <jobs>
            <update_stockqty> 
              <!--The above could be any unique job name-->
              <schedule><cron_expr>0 1 * * *</cron_expr></schedule> 
              <!--The above defines the frequency of the job to run-->
              <run><model>stockimport/import::updateStockQty</model></run> 
              <!--The above tells which model class function to run -->
              <store>1</store>
            </update_stockqty>
            <update_stockqty_de> 
              <!--The above could be any unique job name-->
              <schedule><cron_expr>0 2 * * *</cron_expr></schedule> 
              <!--The above defines the frequency of the job to run-->
              <run><model>stockimport/import::updateStockQty</model></run> 
              <!--The above tells which model class function to run -->
              <store>2</store>
            </update_stockqty_de>
        </jobs> 
    </crontab>
</config>

As you have noticed we have created two jobs update_stock for default store and update_stock_de for germany store and one runs at 1 AM every day and other runs at 2 AM every day respectively.

Now let’s see how can we get the store information in our model class. So now we have changed our updateStockQty function in our model class as follows -:

<?php
class Scommerce_StockImport_Model_Import extends Mage_Core_Model_Abstract
{
    protected function _construct()
    {
        parent::_construct();
        $this-&gt;_init('stockimport/import');
    }

    public function updateStockQty($schedule)
    {
        $jobsRoot = Mage::getConfig()->getNode('crontab/jobs');
        $jobConfig = $jobsRoot->{$schedule-&gt;getJobCode()};
        $storeId = (int) $jobConfig->store;

        $product = Mage::getModel("catalog/product")-&gt;setStoreId($storeId)

        $file = "stockfile.csv"
        $data = array();
        if (file_exists($file)) {
            $parser = new Varien_File_Csv();
             $data = $parser->getData($file);            
        }

        ......
        ......
        ......
    }
}

Please note the parameter $schedule in the function which is by the way available for all the cron job functions and also notice the first three lines in the updateStockQty() function. This is the way you can pass parameter(s) and extract them without any problems.

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Scommerce

14 Comments

  1. Wow, nice page, very informative, i learned a lot…thanks for that information. keep it up.

  2. This blog is definitely an example of a huge help for me since i am just starting a blog myself!!!!!

  3. Nice tutorial.. thanks for sharing..But Where do we need to keep the csv file ?

    • Hi Prerna, you can keep it anywhere you want, generally it is recommended to put in var/import folder if you are import and var/export folder when you are exporting. Hope it answers your query. Thanks

  4. With this code I have Fatal error: Call to a member function getJobCode() on null and I can clearly see in the logs the following line:

    ERR (3): Warning: Missing argument 1 for

    I am using Magento1.7, any hints? The code is the same.
    Thanks

    • It should work, please check the following file on 1.7 version and let us know the outcome -:

      /app/code/core/Mage/Cron/Model/Schedule.php

      Do you have cron job scheduled in the enviroment you are testing?

  5. Setting up cron job helps to let the user know about the deals and discounts, instead of sending emails manually, I was trying to setup cron job in Magento 2, Your post helped me a lot and here, thanks

  6. Magento 1.9.4 does not have app\local\ folder
    Which folder I have to use for config.xml in Step 1 ?

    • Hi Nick, Apologies it should be app/code/local, it has been corrected in the article now. Thanks for pointing it out 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.