Use cron + php script monitor background task script

task1.php

<?php error_reporting(E_ERROR | E_WARNING | E_PARSE);
// redis
$redis = new Redis();
$redis->pconnect(REDIS_HOST, REDIS_PORT);
$redis->auth(REDIS_PASS);
// task
while (true) {
    $task = $redis->rPop('mytask1');
    if ($task !== false) {
        // todo
        continue;
    }
    sleep(1);
}
?>

 

task_monitor.php

<PHP? error_reporting ( E_ERROR | E_WARNING | E_PARSE );
 // task array 
$ Tasks = Array (
     'task1.php', 
    'task2.php', 
    'task3.php', 
    'task4.php', 
    'task5.php' 
    ); 
// Find a running task 
$ cmd = "PS -ef | grep 'task'" ;
 $ RES = shell_exec ( $ cmd );
 $ All = the explode ( "\ the n-", $ RES );
 $ running = Array ();
for($i=0; $i<count($all); $i++){
    $array = explode("php ", $all[$i]);
    $p = trim($array[1]);
    if(!empty($p)) {
        $p = str_replace('/mytask/', '', $p);
        $running[] = $p;
    }
}
echo(date('Y-m-d H:i:s')."\n");
 $ DATE = DATE ( 'YmdHis' );
 // Find the task is not running and start the task 
for ( $ I = 0; $ I < COUNT ( $ Tasks ); $ I ++ ) {
     IF ( the in_array ( $ Tasks [ $ I ], $ running )) {
         echo ( $ Tasks [ $ I .] "IS running \ n-" ); 
    } the else {
         echo ( $ Tasks [ $ I .] "Dead IS \ n-" );
        $cmd = "nohup /usr/bin/php /mytask/".$tasks[$i]." >/mytask/nohup/mytask.log 2>&1 &";
        $res = shell_exec($cmd);
    }
}
echo("\n");
?>

 

Guess you like

Origin www.cnblogs.com/coffee_cn/p/12101382.html