Problem: a long-running PHP script (in this case, a cron-job with a sleep() function in it) was triggering ‘MySQL server has gone away’ errors in a Codeigniter application.

Solution: after each sleep() call, do this:

$this->db->reconnect();

Problem solved.

PS We’re actually using a little function called _randomsleep(), that goes like this:

function _randomsleep()
{
 $sleep = rand(11, 61);
 echo "Sleeping for " . $sleep . " seconds";
 sleep($sleep);
 $this->db->reconnect();
}

We love solving problems, so get in touch with our team if you need some expert advice on any related issues.