123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace console\controllers;
- use backend\models\WorkerScript;
- use yii\console\Controller;
- class MainController extends Controller
- {
- const DURATION = 30;
-
- public function actionIndex()
- {
-
- if ($this->checkMainProcess()) {
- echo "Main process is running. Please check it."; exit;
- }
-
- while (1) {
- $this->checkTasks();
- sleep(self::DURATION);
- };
- }
-
- public function checkTasks()
- {
- echo "\n Checking tasks......";
- $list = WorkerScript::getRunScriptList();
- foreach ($list as $task) {
- if (!is_string($task['controller']) || !is_string($task['action'])) {
- echo "\n this task has error!";
- continue;
- }
- $program = $task['controller'] . '/' . $task['action'];
- $this->execTask($program);
- }
- }
-
- public function execTask($program)
- {
-
- if ($this->checkProcess($program)) {
- return false;
- }
- $dir = dirname(\Yii::$app->getBasePath());
-
- $cmd = "nohup php ".$dir."/yii " . $program." >/dev/null 2>&1 &";
- echo "\n ".$cmd;
- exec($cmd);
- }
-
- public function killTask($program)
- {
-
- if (strlen($program) < 4)
- return false;
- $cmd = "ps -ef | grep " . $program . " | awk '{print $2}' | xargs kill -9";
- exec($cmd);
- return !$this->checkProcess($program);
- }
-
- public function checkMainProcess()
- {
- $cmd = "ps -ef |grep -v grep|grep -v 'sh -c' | grep main";
- exec($cmd, $output);
- return count($output) > 1;
- }
- public function checkProcess($process)
- {
- $cmd = "ps -ef |grep -v grep|grep -v 'sh -c' | grep " . $process;
- exec($cmd, $output);
- return count($output) > 0;
- }
- }
|