scala - 未调用未来的 onComplete 回调
问题描述
解决方案
你的逻辑没有错。我建议您尝试进行一些修改。
import org.slf4j.LoggerFactory
import scala.concurrent.Future
import concurrent.ExecutionContext.Implicits.global
import scala.io.StdIn
import scala.util.{Failure, Success}
object FutureOnComplete extends App {
private val logger = LoggerFactory.getLogger("test")
def logElapsedTime[T](f: => Future[T], description: String): Future[T] = {
val start = System.currentTimeMillis()
f.onComplete(
_ =>
logger.warn(
s"$description took [${System.currentTimeMillis() - start}]"))
f
}
val f = for {
_ <- logElapsedTime(Future(1), "1st task to be executed")
result <- logElapsedTime(Future(2), "2nd task to be executed")
_ <- logElapsedTime(Future(2), "3rd task to be executed")
_ <- logElapsedTime(Future(2), "4th task to be executed")
} yield result
f.onComplete {
case Success(v) =>
logger.info(s"tasks succeeded !!!! $v")
case Failure(ex) =>
logger.error(ex.getMessage)
throw ex
}
StdIn.readLine()
}
- 提高日志级别以
warn
确保您的日志记录不会受到指责。或将其替换为println
- 例如,在您的主线程中等待将来完成
StdIn.readLine()
。这允许异步进程完成并 onComplete 运行。 - 使用
=> Future[T]
name 参数在方法内部开始执行 futurelogElapsedTime
。这只是在未来开始时改变,而不是日志记录的逻辑
推荐阅读
- excel - perl中的Excel链接
- html - HTML 在我的聊天机器人上方放置导航栏
- reactjs - 如果数组中的任何值为假,如何返回布尔值
- flutter - 如何模拟 showDialog 方法
- java - 将此幻数 5 分配给一个有名的常量,并使用该常量代替
- c# - 客户的确认密码在他的 Asp.Net Core 帐户中出现 ModelState 错误
- python - 如何获取在 shell 中使用 python 执行的命令和参数
- mysql - 如何将具有多个主键的 RDBMS 数据传输到 elasticsearch
- java - 是否有可能使用java将字符串时间戳转换为浮点或日期时间
- proxy - 在公司代理后面使用 pgAdmin 4