'Send mail after 15min order completed with Php

I've created a small module in M1.9 to send an email after order completed. There's a cron that runs every 5min and it checks interval -15 -20 min ago and if there's an order it send an email. Everything works pretty fine, but problem is that sometimes it sends 2 mails to the same email. I use a "foreach" element, is it possible to stop it after the first email sent?

  public function customcrontask()
  {
   $time = time();
   $ora = date('Y-m-d H:i:s', $time);
   $toTime = $time - 889;
   $to = date('Y-m-d H:i:s', $toTime);
   $lastTime = $time - 1200; // 60*60*7*24
   $from = date('Y-m-d H:i:s', $lastTime);
   $order_items = Mage::getResourceModel('sales/order_item_collection')
    ->addAttributeToSelect('order_id')
    ->addAttributeToSelect('created_at')
    ->addAttributeToFilter('created_at', array('from' => $from, 'to' => $to))
    ->load();  
    foreach ($order_items as $orderkey => $ordervalue) {
        $eid = $ordervalue->getOrderId();   
// send mail - some variables are not visible here
Mage::getModel('core/email_template')->sendTransactional($template, $sender, $customeremailid, $customername, $vars, $storeId);


Solution 1:[1]

Try this trick:

$x = 0;
    foreach ($order_items as $orderkey => $ordervalue) {
        $eid = $ordervalue->getOrderId();   
        $order           = Mage::getModel("sales/order")->load($eid);
        $customerorderid = $order->getIncrementId();
        $customeremailid = $order->getCustomerEmail();
if($x == 0) {
// send mail - some variables are not visible here
 Mage::getModel('core/email_template')->sendTransactional($template, $sender, $customeremailid, $customername, $vars, $storeId);
$x++;
}

This will help you escape the foreach loop after one count.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WardNsour