【问题标题】:Asynchronous tasks are not done in play framework(scala)异步任务不在播放框架(scala)中完成
【发布时间】:2014-08-23 03:22:39
【问题描述】:

我有一些我想在请求中异步运行的代码。该代码对响应没有影响,所以我像这样运行它

import scala.concurrent.Future    

Database.forURL(url, driver = driver) withSession {
  implicit session =>
// some db changes
//some code that has effect on response like getting userId
//so run synchronously

// now asynchronous code

import play.api.libs.concurrent.Execution.Implicits.defaultContext

Future {
          println("inside Futute, starting")
          val userAuthTable = TableQuery[Tables.UserAuth]
          println("inside Futute, running")
          // some db operations
          println("inside Futute, done")

} // Future block ends
userId


} // session ends

在这里我可以看到控制台上打印的 2 行

inside Futute, starting

inside Futute, running

但我没看到

inside Futute, done

db operations 都没有完成。我能够得到userId,它在Future之外。当我将这些数据库操作放在Future 之外时,它们会被执行。但是为什么不在Future 里面呢?以及为什么前两行打印在控制台上。我正在使用 play 2.3.3 和 scala 2.11

更新

我的代码在 Postgres 会话中,不知何故 Future 块在会话范围之外执行。所以我创建了2个会话,一个用于同步执行db code,另一个用于Future内的异步代码。这工作正常

import scala.concurrent.Future    

val userId = Database.forURL(url, driver = driver) withSession {
    implicit session =>
    // some db changes
    //some code that has effect on response like getting userId
    //so run synchronously
} // session ends

// now asynchronous code
import play.api.libs.concurrent.Execution.Implicits.defaultContext

Future {
println("inside Futute, starting")
Database.forURL(url, driver = driver) withSession {
   implicit session =>
      val userAuthTable = TableQuery[Tables.UserAuth]
      println("inside Futute, running")
      // some db operations
   } // session ends
      println("inside Futute, done")
} // Future ends

感谢@Ryan 和@applicius

【问题讨论】:

  • 执行Future的代码在哪里?
  • 执行Future?我需要执行它吗?我以为您只是将代码放在需要运行的 Future 块中。对不起。我是 Scala 的新手。我刚才在Future 的大括号后面放了一个(),它给出了Not applicable error。但如果未执行未来,为什么要打印第一 2 行?
  • @applicius 如何执行Future
  • 试试Await.result。
  • @applicius 但这不会阻塞。我不想阻止,因为我不在乎该代码何时完成执行。以及为什么只有部分代码被执行的任何想法?

标签: scala playframework-2.0


【解决方案1】:

在未来的末尾添加.recover,以确保不会引发和忽略异常。

【讨论】:

    猜你喜欢
    • 2013-03-28
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2016-07-16
    • 1970-01-01
    相关资源
    最近更新 更多