php-如何执行任务,避免用户被迫等待响应?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-如何执行任务,避免用户被迫等待响应?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2892字,纯文字阅读大概需要5分钟。
内容图文
![php-如何执行任务,避免用户被迫等待响应?](/upload/InfoBanner/zyjiaocheng/685/b4162b68ce1b45b6b44e879e38f0631a.jpg)
用户创建新产品后,在我的应用程序中,然后执行一些操作,例如更新几张表:统计信息,财务,使用情况,库存等.
现在,用户必须等待我完成所有步骤.如果很多用户托盘同时进行,那么等待的时间就更多了,那不是很好.
我的计划是创建一个特殊的TASK_TABLE(product_id,time,task_id),然后在后台BUT中运行以下任务:
>最旧的优先
>不要阻止用户进行下一步操作,
>尽快运行此任务.
如何在Symfony中做到这一点?
最好的方法是什么?
解决方法:
What is the best way to do it?
我不知道这是否是最好的方法,但是处理这种情况的最常见方法(基于提供的少量信息)是:
>解耦一个或多个services中的“操作”(更新统计信息,财务,使用情况,库存等),以便能够重复使用
它在任何地方.
>创建“事件”类(最后是一个简单的DTO),在您的情况下可以是NewProductEvent,用于存储新产品对象:
>创建“侦听器”类NewProductListener,在其中处理“操作”的执行顺序和顺序.
Now users must wait for I’ve finished all steps.
为了避免这种情况,我们必须仅在响应已经提供给客户端之后才能“分派” new_product_created事件,我们可以执行此using a service tag,尤其是kernel terminate event.
但是如何存储产品数据以使其在kernel.terminate中可用?
让我们去实现它.
“事件”类:
use Symfony\Component\EventDispatcher\Event;
use YourApp\YourBundle\Entity\Product;
class NewProductEvent extends Event
{
const EVENT_NAME = 'new_product_created';
protected $product;
public function __construct(Product $newProduct)
{
$this->product = $newProduct;
}
public function getProduct()
{
return $this->product;
}
}
“侦听器”类:
class NewProductListener
{
protected $product;
public function __construct()
{
# then you can inject all dependencies needed to perform your tasks
}
public function onNewProductCreated(Product $newProduct)
{
# here you keep in memory the product data!
$this->product = $newProduct->getProduct();
}
public function performTasks()
{
if ($this->product) {
# here you can put the logic to perform all needed tasks!
}
}
}
侦听器的“服务”定义:
<service id="new_product_listener"
class="YourApp\YourBundle\Event\NewProductListener">
<!-- you can inject in the listener, as argument, each service task you need -->
<!-- <argument type="service" id="financial_operation_service"/>-->
<!-- <argument type="service" id="usage_operation_service"/>-->
<tag name="kernel.event_listener" event="new_product_created" method="onNewProductCreated"/>
<tag name="kernel.event_listener" event="kernel.terminate" method="performTasks"/>
</service>
现在是实际示例(我不注释代码,因为它是自解释的):
// presuming you are in a controller:
$dispatcher = $this->get('event_dispatcher');
$newProduct = //--- I don't know from where it will come.
$event = new NewProductEvent($newProduct);
$dispatcher->dispatch(NewProductEvent::EVENT_NAME, $event);
调度NewProductEvent :: EVENT_NAME(new_product_created)时,会将触发onNewProductCreated方法的产品数据存储在NewProductListener侦听器的$product变量中,以便在触发kernel.terminate事件之后可以使用它!
这样,Symfony将在后台执行所需的任务,而不会降低用户体验.
一些参考:
> The EventDispatcher Component.
> Events and Event Listeners.
内容总结
以上是互联网集市为您收集整理的php-如何执行任务,避免用户被迫等待响应?全部内容,希望文章能够帮你解决php-如何执行任务,避免用户被迫等待响应?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。