在Symfony2中异步调用命令 [英] Asynchronously calling a Command in Symfony2
问题描述
我想从Symfony2中的控制器中异步调用命令.
I want to asynchronously call a Command from within a Controller in Symfony2.
到目前为止,我找到了以下解决方案:
So far i found the following solution:
$cmd = $this->get('kernel')->getRootDir().'/console '.(new MLCJobWorkerCommand)->getName().' '.$job->getId().' 2>&1 > /dev/null';
$process = new Process($cmd);
$process->start();
是否有更好的方法来实现这一目标?
Is there a better way to accomplish this?
我需要Process在后台运行,并且Controller在启动前一个后立即返回.我试过了:
I need the Process to run in background and the Controller to return right after it started the former. I tried:
$cmd = $this->get('kernel')->getRootDir().'/console '
.(new MLCJobWorkerCommand)->getName()
.' '.$job->getId().' 2>&1 > /dev/null & echo \$!';
$process = new Process($cmd);
$process->mustRun();
$params["processid"] = $process->getOutput();
但是在过程完成之前,控制器不会返回响应.
but the Controller doesn't return a Response until the Process has finished.
推荐答案
我同意格里(Gerry)的观点,即如果您希望异步",那么您选择的不是最佳方法
I agree with Gerry that if you want to be "asynchronously" then you selected not the best way
我可以推荐RabbitMQ的替代方案:JMSJobBundle
http://jmsyst.com/bundles/JMSJobQueueBundle/master/installation
I can recommend an alternative of RabbitMQ: JMSJobBundle
http://jmsyst.com/bundles/JMSJobQueueBundle/master/installation
您可以在其中创建控制台命令队列的地方,例如:
Where you can create a queue of you console commands something like:
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;
}
}
这篇关于在Symfony2中异步调用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!