如何在服务中使用 kernel.terminate 事件

How tout use kernel.terminate Event in a Service

我做一个服务运行任务重,这个服务是在Controller中调用的。 为了避免页面加载时间过长,我想要 return HTTP 响应和 运行 之后的繁重任务。

我读到我们可以使用 kernel.terminate 事件来做到这一点,但我不明白如何使用它。

目前我尝试在KernelEvent:TERMINATE上做一个监听器,但我不知道如何过滤,因为监听器只在好的页面上执行作业...

是否可以添加一个函数在事件触发时执行?然后在我的控制器中我只是使用函数来添加我的动作,然后 Symfony 稍后执行它。

感谢您的帮助。

最后,我找到了方法,我在我的服务中使用了 EventDispatcher,并在此处连接了一个监听器 PHP 关闭:http://symfony.com/doc/current/components/event_dispatcher.html#connecting-listeners

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class MyService
{
  private $eventDispatcher;

  public function __construct(TokenGenerator $tokenGenerator, EventDispatcherInterface $eventDispatcher)
  {
   $this->tokenGenerator = $tokenGenerator;
   $this->eventDispatcher = $eventDispatcher;
  }

  public function createJob($query)
 {
    // Create a job token
    $token = $this->tokenGenerator->generateToken();

    // Add the job in database
    $job = new Job();
    $job->setName($token);
    $job->setQuery($query);

    // Persist the job in database
    $this->em->persist($job);
    $this->em->flush();

    // Call an event, to process the job in background
    $this->eventDispatcher->addListener(KernelEvents::TERMINATE, function (Event $event) use ($job) {
        // Launch the job
        $this->launchJob($job);
    });

    return $job;
 }