A background job management instance that obtains a job queue from the database, creates a new process for execution, and waits for the job to end.
Code fragment:
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 Childn";
Exit (0);
Run jobs here
} else{
echo "Waiting for jobn";
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 Finishedn";
Ob_flush ();
}else{
Db::update (' Job_queue ')->set (array (' status ' => '-1 '))
->where (' id ', ' = ', $job [' id '])->execute ();
echo "Child Failedn";
Ob_flush ();
}
}
}
}
else{
if ($requestCount >=10) {
echo "Have a rest, I Have processed JOBSN";
Exit
}
No job to run
echo "No jobn";
Ob_flush ();
Sleep (5);
}
}
}
}