php获取后台Job管理的实现代码

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

<?php defined('SYSPATH') OR die('No direct access allowed.');
class Controller_Jobs extends Controller_Base{
public function before(){
parent::before();
if(Request::$protocol != "cli"){
die("Only cli allowed!\n");
}
}
public function after(){
parent::after();
//do some cleaning tasks
}
private function _execJobCommand($joburi,$paras){
$php_exec = Kohana::config("picsou.php_exec");
$php_index = APPINDEX;
$command_args = array();
$command_args[] = $php_index;
$command_args[] = "--uri=".$joburi;
foreach ($paras as $para => $value){
$command_args[] = "--".$para."=".$value;
}
//var_dump($command_args);exit;
echo "exec commmand:".$php_exec."\n";
pcntl_exec($php_exec,$command_args);
}
/*
* Running jobs in queues
*/
public function action_run(){
$requestCount = 0;
while(true){
$sql = "select * from job_queue where status='1' and approved='1' order by id";
$jobs = DB::query(Database::SELECT,$sql)->execute()->as_array();
if($jobs){
foreach ($jobs as $job){
$requestCount ++;
//update the jobs status as running
DB::update('job_queue')->set(array('status'=>'2'))
->where('id','=',$job['id'])->execute();
$job_pid = pcntl_fork();
if($job_pid == -1){
die("Could not fork Child");
} else if($job_pid == 0 ){
$this->_execJobCommand($job['job_uri'],json_decode($job['paras'],true));
echo "finish Child\n";
exit(0);
//run jobs here
} else{
echo "Waiting for job\n";
ob_flush();
$child_pid = pcntl_waitpid($job_pid,$status, WUNTRACED);
echo "waitpid end:".$status."\n";
if($status == 0){
//job completed
DB::update('job_queue')->set(array('status'=>'999'))
->where('id','=',$job['id'])->execute();
echo "Child Finished\n";
ob_flush();
}else{
DB::update('job_queue')->set(array('status'=>'-1'))
->where('id','=',$job['id'])->execute();
echo "Child Failed\n";
ob_flush();
}
}
}
}
else{
if($requestCount >=10){
echo "Have a rest, I have processed 10 jobs\n";
exit;
}
//no job to run
//echo "No job\n";
ob_flush();
sleep(5);
}
}
}
}

相关文章

php中base64_decode与base64_encode加密解密函数实例

本文实例讲述了php中base64_decode与base64_encode加密解密函数。分享给大家供大家参考。具体分析如下: 这两个函数在php中是用得对php代码进行加密与解密码的b...

PHP Reflection API详解

PHP Reflection API是PHP5才有的新功能,它是用来导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。 PHP Reflection API有: class...

php的debug相关函数用法示例

本文实例讲述了php的debug相关函数用法。分享给大家供大家参考,具体如下: loginfo函数: function loginfo($format) { $args = fu...

thinkphp中多表查询中防止数据重复的sql语句(必看)

下面先来看看例子: table id name 1 a 2 b 3 c 4 c 5 b 库结构大概这样,这只是一个简单的例子,实际情况会复杂得多。 select *, c...

纯php生成随机密码

纯php生成随机密码

php生成一个随机的密码,方便快捷,可以随机生成安全可靠的密码。 分享代码如下 <?php header("Content-type:text/html;chars...