简体   繁体   中英

MySQL Connection Closing During Parallel Cron Tasks

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

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM