Set cron job to module stock status
-
09-10-2020 - |
Question
Here is great module for stock Status From Enru magento-stock-status
but now issue is its works on save action.
I want to set it Cron Job. cron job run On Daily basis Kindly let me know how can i set cron job For this module strongly thanks in Advance
Solution
The simplest solution would be setup a cron job either through a custom module or in magento-stock-status
module and then fire the event catalog_product_stock_item_mass_change
with product ids which you need to update in cron job.
So this answer assumes you know how to setup cron for Magento and you are using a custom module Namespace_Module
.
Step 1 : Setup cron job
File : app\code\local\Namespace\Module\etc\config.xml
<config>
<models>
<namespace_module>
<class>Namespace_Module_Model</class>
</namespace_module>
</models>
<crontab>
<jobs>
<update_product_stock_cron>
<schedule>
<cron_expr>* 0 * * *</cron_expr>
</schedule>
<run>
<model>namespace_module/observer::updateProductStock</model>
</run>
</update_product_stock_cron>
</jobs>
</crontab>
</config>
Here you can set the cron time under <cron_expr>
section. The given experssion is for running the script once in a day.
From the xml configuration, what we specified is, we need to run the observer function updateProductStock()
once in a day.
Step 2 : Define Observer
File : app\code\local\Namespace\Module\Model\Observer.php
class Namespace_Module_Model_Observer
{
public function updateProductStock()
{
//all product collection
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('id');
$productIds = $collection->getAllIds();
//fire the event
Mage::dispatchEvent('catalog_product_stock_item_mass_change', array(
'products' => $productIds,
));
return $this;
}
}
Here it loads all products and then pass all product ids by firing the event catalog_product_stock_item_mass_change
. This event is already observing by the module "magento-stock-status". It will thus update stock status of all products which we passed through the event.
So make sure you pass only those products which you really need to update.
This method has a small problem if there are modules which already listen to the event catalog_product_stock_item_mass_change
. So if firing this event may cause some severe issues in your Magento instance, then instead of firing, you need to replicate the function Enru_StockStatus_Model_Observer::massStockChange()
in your custom module.
Hope that will help you.