Below code worked for me.
private function cancelPendingPayments() {
$fromDate = date('Y-m-d H:i:s', strtotime('-2 hour'));
$toDate = date('Y-m-d H:i:s', strtotime(now()));
$orderCollection = Mage::getResourceModel('sales/order_collection');
$orderCollection->addFieldToFilter('status', 'pending_payment')
->addFieldToFilter('updated_at', array( 'from' => $fromDate, 'to' => $toDate, 'date' => true ))
->getSelect()
->order('entity_id')
->limit(20);
if( count( $orderCollection ) < 1 ) {
return;
}
foreach( $orderCollection as $order ) {
$difference = $this->getDifference($order);
if( ( $difference >= 30 ) && ( $difference < 45 ) ) {
$emailVariables = $this->pendingPaymentsVariables( $order );
$this->prepareEmail( Mage::getStoreConfig('clearbasket_settings/email_template/pending_payment_notify'),
$emailVariables, $emailVariables['orderdetails']['customername'], $emailVariables['orderdetails']['customeremail'] );
$history = $order->addStatusHistoryComment('Notification email sent - Cron Jobs',false);
$history->setIsCustomerNotified(false);
$order->save();
}
if( $difference > 60 ) {
if(!$order->canCancel()) {
Mage::log('Order cannot be canceled anymore.',null,"order.log");
}
else {
$order->cancel();
}
$order->setData('state', "canceled");
$order->setStatus("canceled");
$order->setData('state', Mage_Sales_Model_Order::STATE_CANCELED);
$order->setActionFlag(Mage_Sales_Model_Order::ACTION_FLAG_CANCEL, true);
Mage::log('Order cancel after : '.$difference, null, "order.log");
$history = $order->addStatusHistoryComment('Order marked as cancelled due to pending payment - Cron Jobs.', false);
$history->setIsCustomerNotified(false);
$order->save();
}
}
}
Please refer the link below for sending notification emails before cancelling and cron jobs.
https://www.pearlbells.co.uk/cancel-pending-payments-magento/