如何在服务中使用 kernel.terminate 事件 [英] How tout use kernel.terminate Event in a Service

查看:37
本文介绍了如何在服务中使用 kernel.terminate 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个运行繁重任务的服务,这个服务是在控制器中调用的.为了避免页面加载时间过长,我想返回 HTTP 响应并在之后运行繁重的任务.

I do a service that run an heavy task, this service is call in a Controller. To avoid a too long page loading, I want return the HTTP Response and run the heavy task after.

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

I've read we can use kernel.terminate event to do it, but I don't understand how to use it.

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

For the moment I try to do a Listener on KernelEvent:TERMINATE, but I don't know how to filter, for the Listener only execute the job on the good page...

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

Is it possible to add a function to execute on when the Event is trigger ? Then in my controller I juste use the function to add my action, and Symfony execute it later.

感谢您的帮助.

推荐答案

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

Finally, I've find how to do it, I use the EventDispatcher in my Service and I connecting a Listener here a PHP Closure: 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;
 }

这篇关于如何在服务中使用 kernel.terminate 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆