简体   繁体   English

如何在Play中通过请求启动后台线程! 框架?

[英]How do I start a background thread with a request in the Play! framework?

I've been looking into the Play! 我一直在寻找Play! framework and I'm interested in converting one of my projects over to it. 框架,我对将我的项目之一转换成它感兴趣。 However, this project requires that long-running threads be spawned upon a user action, but the result of the thread is not returned to the user via a normal request-response method. 但是,此项目要求在用户操作时生成长时间运行的线程,但是线程的结果不会通过常规的请求-响应方法返回给用户。 Instead, the user is redirected to a page which monitors the threads they have started. 而是将用户重定向到一个页面,该页面监视他们已启动的线程。

So, I'm wondering how I can create a user action that creates a thread whenever a user POSTs to /start, but the thread automatically goes into the "background" and the user receives a response such as "ok" or even a redirect, rather than the output of the thread. 因此,我想知道如何创建一个用户操作,该操作将在用户POST到/ start时创建一个线程,但是该线程自动进入“后台”,并且用户收到诸如“ ok”甚至重定向的响应。 ,而不是线程的输出。

I also want some degree of control over the threads; 我还希望对线程进行某种程度的控制; in other words, I don't just want to create a thread and leave it to run. 换句话说,我不仅要创建一个线程并使其运行。 I want to have some kind of global reference point so that a user can stop a thread once it has been started (eg by visiting /stop). 我想拥有某种全局参考点,以便用户可以在线程启动后停止它(例如,通过访问/ stop)。

Play provides special Job which can be run in background periodically or on application startup, but I don't think it is suitable for you. Play提供了特殊的Job,可以在后台定期运行或在应用程序启动时运行,但我认为它不适合您。

In your case, you can simply spawn new Thread or submit new task to Executor , using Java API and return response to user. 在您的情况下,您可以简单地使用Java API生成新的Thread或将新任务提交给Executor并将响应返回给用户。 For stopping Thread you can use standard approach with loop and interrupted flag. 要停止Thread ,可以使用带有循环和中断标志的标准方法。 Nothing special from play framework here, just regular java api. 这里的play框架没什么特别的,只有常规的Java api。

I wouldn't spawn new Thread instances but use Actor instances instead. 我不会产生新的Thread实例,而是使用Actor实例。 They're a more simple and robust model for doing non-blocking tasks in the background. 它们是用于在后台执行非阻塞任务的更简单,更强大的模型。

Refer to the Play and Akka documentation for details. 有关详细信息,请参阅PlayAkka文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM