我做了一个运行繁重任务的服务,该服务在控制器中调用。
为了避免页面加载时间过长,我想返回 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)