Asynchronously calling a Command in Symfony2

前端 未结 2 434
故里飘歌
故里飘歌 2021-01-02 14:23

I want to asynchronously call a Command from within a Controller in Symfony2.

So far i found the following solution:

$cmd = $this->get(\'kernel\')         


        
2条回答
  •  鱼传尺愫
    2021-01-02 14:47

    I agree with Gerry that if you want to be "asynchronously" then you selected not the best way

    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;
        }
    }
    

提交回复
热议问题