关闭php连接

时间:2013-03-11 01:12:41

标签: php

我有一个cron Job每5分钟运行一次脚本。但是,似乎脚本一旦运行就不会关闭连接。如何在此脚本中关闭连接?

function __construct($config)
{
    $this->server = $config['server'];
    $this->certificate = $config['certificate'];
    $this->passphrase = $config['passphrase'];

    // Create a connection to the database.
    $this->pdo = new PDO(
        'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], 
        $config['db']['username'], 
        $config['db']['password'],
        array());

    // If there is an error executing database queries, we want PDO to
    // throw an exception.
    $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // We want the database to handle all strings as UTF-8.
    $this->pdo->query('SET NAMES utf8');
}

// This is the main loop for this script. It polls the database for new
// messages, sends them to APNS, sleeps for a few seconds, and repeats this
// forever (or until a fatal error occurs and the script exits).
function start()
{
    writeToLog('Connecting to ' . $this->server);

    if (!$this->connectToAPNS())
        exit;

    while (true)
    {
        // Do at most 20 messages at a time. Note: we send each message in
        // a separate packet to APNS. It would be more efficient if we 
        // combined several messages into one packet, but this script isn't
        // smart enough to do that. ;-)

        $stmt = $this->pdo->prepare('SELECT * FROM messages WHERE time_sent IS NULL LIMIT 20');
        $stmt->execute();
        $messages = $stmt->fetchAll(PDO::FETCH_OBJ);

        foreach ($messages as $message)
        {
            if ($this->sendNotification($message->id, $message->token, $message->payload))
            {
                $stmt = $this->pdo->prepare('UPDATE messages SET time_sent = NOW() WHERE id = ?');
                $stmt->execute(array($message->id));
            }
            else  // failed to deliver
            {
                $this->reconnectToAPNS();
            }
        }

        unset($messages);           
        sleep(5);
    }
}

1 个答案:

答案 0 :(得分:1)

我可能误读了,但显然你每隔5分钟启动一个不退出的脚本(无限循环)。所以你正在堆叠实例,直到地球(或更适度的,你的服务器)最终爆炸。

为了回答你的问题,当脚本执行结束时,PHP会自动释放所有资源,包括数据库连接。

当脚本运行很长时间(如无限),或者存在非常具体的内存注意事项时,可以使用unset($foo)手动释放资源或$foo = null。[1]

数据库连接也可以通过这种方式关闭和释放,只需unset($this->pdo)


[1]另见What's better at freeing memory with PHP: unset() or $var = null