YIi2 console中
<?php
/**
* Created by PhpStorm.
* User: weiqiang
* Date: 2018/8/17
* Time: 下午4:56
*/
namespace app\modules\console\controllers;
use yii\console\Controller;
use Yii;
class TimeController extends Controller
{
const REDIS_KEY = "time_command";
public function actionIndex()
{
$redis = Yii::$app->get('redis');
$appDirectory = Yii::getAlias('@app/modules/console/yii');
$file = Yii::getAlias('@app/web/config/timeCommand/config.json');
$jsonArr = json_decode(file_get_contents($file), true);
$commandList = $jsonArr['commandList'];
$phpDirectory = $jsonArr['phpDirectory'];
$start = $jsonArr['start'];
while($start){
$jsonArr = json_decode(file_get_contents($file), true);
$start = $jsonArr['start'];
sleep($jsonArr['interval']);
foreach ($jsonArr['commandList'] as $name=>$content) {
$pid = pcntl_fork(); // 启动一个字进程,并返回进程号
if($pid == -1){
//进程创建失败
}else if(!$pid){
$time = time();
if (strtotime($content['start'])<=$time&&strtotime($content['end'])>=$time){
$tmp = $redis->HGET(static::REDIS_KEY,$name);
if ($time>=$tmp+$content['interval']-5){
$redis->HSET(static::REDIS_KEY,$name,$time);
$res = shell_exec($phpDirectory." ".$appDirectory." ".$content['command']);
$this->myLog($res);
}
}
//$this->myLog("Time/Index succeed");
exit;
}else{
pcntl_wait($status, WNOHANG);//把僵尸进程关闭
//这里就是 父进程在创建完子进程后 要执行的部分,可以写一些信号控制等内容
}
}
}
}
private function myLog($string){
$directory = Yii::getAlias('@app/web/config/timeCommand/log');
$date = date("Ymd");
$myfile = fopen($directory."/".$date.".log", "a+");
$dateTime = date("Y-m-d H:i:s");
fwrite($myfile, "[".$dateTime."] ".$string."\n");
fclose($myfile);
}
public function actionIndex1()
{
sleep(1);
echo "index1 succeed";
}
public function actionIndex2()
{
echo "index2 succeed";
}
}
config.json内容
{
"commandList":{
"everyDay":{
"command": "console/time/index1",
"start": "2018-10-10 00:00:00",
"end": "2018-10-20 00:00:00",
"interval": "6"
},
"everyMonth":{
"command": "console/time/index2",
"start": "2018-10-01 00:00:00",
"end": "2018-10-20 00:00:00",
"interval": "6"
}
},
"interval":6,
"start":false,
"phpDirectory":"/usr/local/opt/php@7.1/bin/php"
}