Magento 1.8 – Update Order Status Using Cron Job

ce-1.9.0.1cronmagento-1.8order-status

I am trying to setup a Cron to automatically update order statuses that have a are in a "Processing" state in Magento.

Here is what I have so far

config.xml

    <orders>
        <schedule><cron_expr>0 9,11,13,15,17 * * *</cron_expr></schedule>
        <!--schedule><cron_expr>*/15 * * * *</cron_expr></schedule-->
        <run><model>orders/Status::cron</model></run>
    </orders>

</jobs>

And inside Status.php

public function updateOrderStatus($order)
{

    $order->setOrderStatus(self::STATUS_PACKING);

    $order->save();

}

What I would like to do is change any orders from "Processing" to "Packing" but I can't seem to find a way to do it…

If anyone knows any good resources please share.

Best Answer

There are a few things that seem to need correcting:

  • The xml is calling the wrong function

<run><model>orders/status::cron</model></run>

This line says to look in the orders module (though that it is a bit of an oversimplification) and look for a Model called Status and run the cron() function

What you probably want to do is change the line to this:

<run><model>orders/status::updateOrderStatus</model></run>

  • The updateOrderStatus() function does not have access to your orders

Even though the function has a parameter called $order it does not act like an observer where the object is there automatically.

In other words: the order collection needs to be loaded with the following code:

Mage::getResourceModel('sales/order_collection');

The collection should be narrowed to what you need (see below).

The function should end up looking like this:

public function updateOrderStatus()
{
    // lets get all the orders that their status is 'pending'
    $orders = Mage::getResourceModel('sales/order_collection')
         ->addFieldToFilter('status', 'pending');
     // loop through each order, set the new status and try to save, if it fails, log why (this way we'll know)
     foreach($orders as $order){
            $order->setOrderStatus(self::STATUS_PACKING);
            try{
                $order->save();
                }catch(Exception $e){
                  Mage::log('Couldn\'t save order' . $order->getId());
                  Mage::log($e->getMessage());
                 }
      }
}
Related Topic