MySQL Connection Closing During Parallel Cron Task

2019-08-04 06:32发布

问题:

I have written a Zend Framework based cron service for parallel tasks based on these two blog articles:

  • Cron tasks in Zend Framework apps
  • Zend Framework Cron Tasks in Parallel

In summary, the cron services uses pcntl_fork() to spawn the tasks in parallel.

Running a single task with the service works without issues, but when I add a second task, I get this MySQL error:

General error: 2006 MySQL server has gone away

My best guess is that a child thread ends before the other and the MySQL connection is implicitly closed. If this is the case, how do I ensure that the connection stays open until the parent thread closes?

回答1:

After reading the comments on pcntl_fork() and this SO question, it was indeed the issue with children sharing the parent connection. I have added this code to create a new MySQL connection after forking, and it seems to have fixed the problem:

// give this thread its own db connection
$settings = Zend_Registry::get('settings');
$db = Zend_Db::factory(
    $settings->db_adapter,
    array(
        'host' => $settings->db_host,
        'username' => $settings->db_user,
        'password' => $settings->db_pass,
        'dbname' => $settings->db_name,
    )
);
$db->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Db_Table::setDefaultAdapter($db);