Symfony执行长时间运行的脚本

时间:2015-04-20 13:38:09

标签: php c++ symfony process symfony-process

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

现在我通过shell_exec()

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

如果我一直刷新页面,脚本运行正常,但如果我去AFK,脚本会被PHP服务器进程终止(/ usr / bin / php-cgi)。

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

2 个答案:

答案 0 :(得分:2)

您可以查看Symfony Process Component:http://symfony.com/doc/current/components/process.html

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

您将能够运行您的流程。

答案 1 :(得分:0)

您可以创建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;
    }
}