场景:
长时间数据库操作致使DB会话超时,多发在后台脚本,可以预估脚本执行时间,在每次执行前重新获取DB预防程序中断
/**
* Get new mysql conn* @param $timeout int default 1440s optional
* @return object
**/
public static function getNewDb($timeout = 1440) {
if(self::$db)
self::CloseConnection();
if (self::$db == null)
{
self::$db = Yii::app()->getComponent('database');
if (self::$db instanceof CDbConnection)
{
self::$db->setActive(true);
self::$db->createCommand('set session wait_timeout = '. $timeout)->execute();
return self::$db;
}
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
return self::$db;
}
/**
* Closed specific conn
* @return void
**/
public static function CloseConnection() {
if(self::$db !== null) {
self::$db->setActive(FALSE);
self::$db = null;
}
}