Symfony 执行长 运行 脚本

Symfony execution of long running script

我正在使用 Symfony2,我想 运行 一个用 C++ 编写的长脚本(例如 60 分钟)。

现在我通过 shell_exec():

$pid = shell_exec('nohup my/program/written/in/c++.out some arguments > /dev/null 2>/dev/null & echo $!');

如果我不断刷新页面,脚本 运行 没问题,但如果我挂机,脚本会随着 PHP 服务器 (/usr/bin/php-cgi) 的进程而终止。

有没有办法将 C++ 程序与 PHP 服务器进程隔离开来?使用 nohup 时,进程的 ppid = 1,因此它应该被隔离,但事实并非如此。

您可以查看 Symfony 进程组件:http://symfony.com/doc/current/components/process.html

$process = new Process('nohup my/program/written/in/c++.out some arguments');
$process->run();

您将能够运行您的流程。

您可以创建 symfony2 控制台命令 "myapp:my-command-name",它将 运行 您的 c++ 命令

class MyStandaloneCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('myapp:my-command-name')
            ->setDescription('Will run standalone c++')
            ->addArgument('arg1', InputArgument::REQUIRED, 'Some arg');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {   
        $arg1 = $input->getArgument('arg1');
        $result = shell_exec('nohup my/program/written/in/c++.out '.$arg1.' 2>&1');

        $output->writeln('My cool command is started');

        return true;
    }

}

然后使用JMSJobBundle
http://jmsyst.com/bundles/JMSJobQueueBundle/master/installation

您可以在其中创建控制台命令队列,例如:

class HomeController ... {
 // inject service here
 private $cronJobHelper;
 // inject EM here
 private $em;
public function indexAction(){

 $job = $this->cronJobHelper->createConsoleJob('myapp:my-command-name', $event->getId(), 10);
        $this->em->persist($job);
 $this->em->persist($job);
$this->em->flush();
}


use JMS\JobQueueBundle\Entity\Job;

class CronJobHelper{

    public function createConsoleJob($consoleFunction, $params, $delayToRunInSeconds, $priority = Job::PRIORITY_DEFAULT, $queue = Job::DEFAULT_QUEUE){
        if(!is_array($params)){
            $params = [$params];
        }

        $job = new Job($consoleFunction, $params, 1, $queue, $priority);
        $date = $job->getExecuteAfter();
        $date = new \DateTime('now');
        $date->setTimezone(new \DateTimeZone('UTC')); //just in case
        $date->add(new \DateInterval('PT'.$delayToRunInSeconds.'S')); 
        $job->setExecuteAfter($date);

        return $job;
    }
}