简体   繁体   中英

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

I've been looking into the 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.

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).

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.

In your case, you can simply spawn new Thread or submit new task to Executor , using Java API and return response to user. For stopping Thread you can use standard approach with loop and interrupted flag. Nothing special from play framework here, just regular java api.

I wouldn't spawn new Thread instances but use Actor instances instead. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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