0

我有一个 cron 作业每 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);
    }
}
4

1 回答 1

1

我可能读错了,但显然你每 5 分钟启动一个不退出的脚本(无限循环)。因此,您正在堆叠实例,直到地球(或更简单地说,您的服务器)最终爆炸。

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

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

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


[1] 另请参阅PHP 释放内存的优势:unset() 或 $var = null

于 2013-03-11T01:49:04.857 回答