Magento – SQLSTATE[HY000]: General error: 2006 MySQL server has gone away on running cron job magento

cronevent-observermagento-1.7MySQL

I am working on site .suddenly i got this message on running cron job multiple times.i check my website for the same error but it works.I remove the cache and try to exit the code but after the error no code works in cron job.This is my code perhaps someone can guide me where the issue is :

<?php

class Namespace_Module_Model_Observer 
{

   public function importemails(Varien_Event_Observer $observer)
   {
        echo "Hi Dear";exit();

      /* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'myid@gmail.com';
$password = 'mypass';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

/* grab emails */
$emails = imap_search($inbox,'ALL');

/* if emails are returned, cycle through each... */
if($emails) {

  /* begin output var */
  $output = '';

  /* put the newest emails on top */
  rsort($emails);

  /* for every email... */
  foreach($emails as $email_number) {

    /* get information specific to this email */
    $overview = imap_fetch_overview($inbox,$email_number,0);
    $message = imap_fetchbody($inbox,$email_number,2);

    /* output the email header information */
    $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
    $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
    $output.= '<span class="from">'.$overview[0]->from.'</span>';
    $output.= '<span class="date">on '.$overview[0]->date.'</span>';
    $output.= '</div>';

    /* output the email body */
    $output.= '<div class="body">'.$message.'</div>';
  }

  echo $output;
} 

/* close the connection */
imap_close($inbox);

  }

}

this code works for several hours but all of sudden it showing me the error of mysql gone away.Thanks in advance

Best Answer

Based on the code I see above, the connection to the database is sitting idle while you iterate over all the emails. My guess is that the code here is taking longer than MySql is configured to wait before closing an idle connection, I.e. The value of the wait_timeout setting which IIRC is 300 (5 min) by default.

Without seeing the exact backtrack of the error, I would assume it's coming after this finishes processing, when the cron dispatcher attempts to update the cron task as complete in the cron_schedule table.

Out of the box, Magento does not attempt to reopen connections MySql has closed and will fail if it's been closed and it tries to use it.

To fix this, you'll either need to up the timeout setting in the mysql stack or ping the database to maintain an open connection.