<?php
/**
 * 创建进程
 * @author KevinXie
 *
 */
class Scrontab_Process
{
    public $task;

    /**
     * 创建一个子进程
     * @param $task
     */
    public function create_process($id, $task)
    {
        $this->task = $task;
        $process = new swoole_process(array($this, "run"));
        if (!($pid = $process->start())) {
			return ;
        }
        //记录当前任务
        Scrontab_Class::$task_list[$pid] = array(
            "start" => microtime(true),
            "id" => $id,
            "task" => $task,
            "type" => "crontab",
            "process" =>$process,
        );
//        swoole_event_add($process->pipe, function ($pipe) use ($process) {
//            $task = $process->read();
//            list($pid, $sec) = explode(",", $task);
//            if (isset(Scrontab_Class::$task_list[$pid])) {
//                $tasklist = Scrontab_Class::$task_list[$pid];
//                Scrontab_Class::$delay[$pid] = array("start"=>time() + $sec,"task"=>$tasklist["task"]);
//                $process->write($task);
//            }
//        });
    }

    /**
     * 子进程执行的入口
     * @param $worker
     */
    public function run($worker)
    {
        $class = $this->task["classname"];
        $worker->name(Scrontab_Class::$process_name . "_" . $class . "_" . $this->task["id"]);
        $class::factory()->run($this->task["args"]);
        self::_exit($worker);
    }

    private function _exit($worker)
    {
        $worker->exit(1);
    }

}

