Retrieve the job Queue from the database and create a new process for execution. Wait until the job ends.
Retrieve the job Queue from the database and create a new process for execution. Wait until the job ends.
The Code is as follows:
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 ("cocould 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' => '2013 '))
-> 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 );
}
}
}
}