在后台运行框架 Scala 运行 作业

Play framework Scala run job in background

有什么方法可以从控制器触发作业(不等待它完成)并向用户显示作业将在后台 运行ning 的消息?

我有一种控制器方法需要很长时间才能完成 运行。所以我想让 运行 脱机并向用户显示它将在后台 运行ning 的消息。

我尝试了 Action.async,如下所示。但是 Future 对象的处理仍然需要更多时间并超时。

def submit(id: Int) = Action.async(parse.multipartFormData) { implicit request =>
    val result = Future {
      //process the data
    }
   result map {
      res =>
      Redirect(routes.testController.list()).flashing(("success", s"Job(s) will be ruuning in background."))
   }
}

docs状态:

By giving a Future[Result] instead of a normal Result, we are able to quickly generate the result without blocking. Play will then serve the result as soon as the promise is redeemed.

The web client will be blocked while waiting for the response, but nothing will be blocked on the server, and server resources can be used to serve other clients.

您可以将客户端代码配置为使用 ajax 请求并在页面的某些部分显示 Waiting for data 消息,而不会阻止网页的其余部分来自加载。

您还可以return一个结果,而无需以"fire and forget"的方式等待未来的结果

def submit(id: Int) = Action(parse.multipartFormData) { implicit request =>     
    Future {
      //process the data
    }
    Redirect(routes.testController.list()).flashing(("success", s"Job(s) will be running in background."))
}

我也尝试了 "Futures.timeout" 选项。它似乎工作正常。但我不确定它是否正确。

result.withTimeout(20.seconds)(futures).map { res =>
  Redirect(routes.testController.list()).flashing(("success", s"Job(s) will be updated in background."))
}.recover {
  case e: scala.concurrent.TimeoutException =>
    Redirect(routes.testController.list()).flashing(("success", s"Job(s) will be updated in background."))
}