代码改变世界

cakephp2 框架下的 持久处理 不丢失数据库连接 后台挂起执行。

2018-08-16 09:36  Dooun  阅读(201)  评论(0)    收藏  举报

前言 : 利用cakephp2 自带的数据库连接方式的话,持久处理中会丢失数据库连接,以下是解决方案之一。这里顺便把怎么在Linxu上后台挂起执行也写了下。

1 : 批处理触发器

2 : 批处理实体

3 : 执行方法 {

  3.1 : 正常执行,

  3.2 : 后台挂起,

  3.3 : 后台挂起,并且禁止输出nohup.out文件,

}

4 : 杀死挂起的后台进程 {

  4.1 查看进程,

  4.2 杀死进程

}

 

1, 批处理触发器

 1 // 引入你要用的控制器, 这里是SomeController
 2 App::uses('SomeController', 'Controller');
 3
 4 /**
 5  * Class SomeShell
 6  * @property SomeController SomeController
 7  */
 8 class SomeShell extends AppShell {
 9
10     // 初始化处理
11     function startup(){
12         parent::startup();
13         $this->SomeController = new SomeController();
14     }
15
16     public function infiniteBatch() {
17
18         // 执行对应的Action
19         $this->SomeController->infiniteBatch();
20     }
21
22 }

 

2, 批处理实体控制器

 1     // app/Controller/SomeController.php
 2     public function infiniteBatch() {
 3
 4         // 发送方向 企业到个人
 5         define("DIRECTION_EMPLOYER_TO_APPLICANT", 1);
 6         // 发送方向 个人到企业
 7         define("DIRECTION_APPLICANT_TO_EMPLOYER", 0);
 8         // 新消息flag 有新消息
 9         define("HAVE_NEW_MESSAGE_YES", 1);
10         // 新消息flag 没有新消息
11         define("HAVE_NEW_MESSAGE_NO", 0);
12
13         // 再循环的外面拿到数据库配置
14         $this->模型 = ClassRegistry::init("SessionMessage");
15         $DbConfig = $this->模型->getDataSource()->config;
16
17         // 执行一个无限循环
18         while (true) {
19             $this->log("开始", 'rcvMail');
20             // 初始化模型
21             $smModel = ClassRegistry::init("模型");
22             // 连接数据库 default 是数据库配置名 查看 database.php
23             ConnectionManager::create('default', $DbConfig);
24             // 把数据库连接交给模型
25             $smModel->setSource('表名');
26             // 连接
27             $smModel->getDataSource()->connect();
28
29
30             // 执行数据库操作
31             $result = $this->模型->find('first');
32
33             // 获取数据库配置
34             $dbConfigName = $smModel->useDbConfig;
35
36             // 断开连接
37             $smModel->getDataSource()->disconnect();
38
39             // 删除数据库配置
40             ConnectionManager::drop($dbConfigName);
41
42             // 每次循环玩休息一定时间
43             sleep(10);
44         }
45     }

 

3, 执行批处理 (Linux 环境下)

# 假设项目在 /var/www/html目录下

# 3.1 普通执行
/var/www/html/app/Console/cake.php Some infiniteBatch
# 3.2 挂起执行
nohup /var/www/html/app/Console/cake.php Some infiniteBatch&
# 3.3 挂起执行,并且禁止输出nohup.out文件
nohup /var/www/html/app/Console/cake.php Some infiniteBatch >/dev/null 2>&1 &

 

4, 查看和杀死cakephp挂起的进程

4.1 查看进程

ps -aux|grep cake.php|grep -v grep

得到这样的东西

www      29475  0.8  0.3 264024 29660 ?        S     6月14  99:35 /usr/bin/php -q /var/www/html1/app/Console/cake.php Some infiniteBatch

4.2 杀死进程

kill 29475

 

谢谢阅览,如有不明点可留言 : )