cakephp 3.1 mysql has gone away

1k Views Asked by At

I have a Shell script that runs continuously on a loop.

It checks the database for records and alters them if needs be.

        set_time_limit(0);
        while(true){
            try{
                $this->out(mysql_ping());
                $companies = $this->findCompanies();            
                $companies = $this->reduceCompanies($companies, $rules);
                $this->processCompanies($companies);

            }catch (\Exception $e){
                Log::write('debug', $e->getMessage());
            $this->out($e->getMessage());
            }
        sleep(3);
        }

Problem I'm having is this script seems to run ok, but then randomly will throw: '2006 MySQL server has gone away' I've tried to put some stuff in the exception catch to reconnect to the mysql server such as :

     }catch (\Exception $e){
                    if(!mysql_ping()){//tried 
    $this->connection->reconnect();  //also tried
$this->Company->getDatasource()->reconnect();   neither seem to work.
                    }}

Any suggestions how to reconnect to the db?

1

There are 1 best solutions below

0
On

I had a similar Problem where the Shell is running in an infinite loop.

Add the use for the ConnectionManager:

use Cake\Datasource\ConnectionManager;

Get the connection before the loop:

$connection = ConnectionManager::get('default');

In the loop, shortly before you first need the connection, check if you are still connected and do a connect if you are disconnected:

if(!$connection->isConnected()) {
    $connection->connect();
}

If your Shell has a state where it is waiting for a longer time, you could try to manually disconnect and do a new connect when you need the connection again:

if($connection->isConnected()) {
    $connection->disconnect();
}