Multithreading 在Scala中周期性调用一个函数,而另一个昂贵的函数正在计算

Multithreading 在Scala中周期性调用一个函数,而另一个昂贵的函数正在计算,multithreading,scala,design-patterns,concurrency,Multithreading,Scala,Design Patterns,Concurrency,我有一个需要很长时间计算的函数 def longFunc={Thread.sleep30000;true} 当这个函数正在计算时,我需要ping一个服务器,以便它一直等待我函数的值。但是为了便于讨论,假设我需要在longFunc运行时每5秒运行一次以下函数 def shortFunc=打印打印服务器!我还活着! 要做到这一点,我有下面的代码片段,它可以工作,但我想知道是否有更好的模式用于此场景 导入scala.concurrent.{wait,Future} 导入scala.concurrent

我有一个需要很长时间计算的函数

def longFunc={Thread.sleep30000;true} 当这个函数正在计算时,我需要ping一个服务器,以便它一直等待我函数的值。但是为了便于讨论,假设我需要在longFunc运行时每5秒运行一次以下函数

def shortFunc=打印打印服务器!我还活着! 要做到这一点,我有下面的代码片段,它可以工作,但我想知道是否有更好的模式用于此场景

导入scala.concurrent.{wait,Future} 导入scala.concurrent.duration_ 导入java.util.{Timer,TimerTask} 导入scala.concurrent.ExecutionContext.Implicits.global def shortFunc=打印打印服务器!我还活着! def longFunc={Thread.sleep30000;true} val funcFuture=未来{longFunc} val定时器=新定时器 def pinger=新时间任务{ def运行:单位=shortFunc } timer.schedulepinger,0L,5000L//每两分钟ping一次服务器,表示您仍在工作 val done=wait.resultfuncFuture,1分钟 平格,取消
实际上,我不确定这是更优雅的图案还是只是为了好玩:

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

def waiter[T](futureToWait:Future[_], waitFunc: => T, timer: Duration) = Future {
  while (!futureToWait.isCompleted) {
    Try(Await.ready(futureToWait, timer))
    waitFunc
  }
}

def longFunc = {Thread.sleep(30000); true}
def shortFunc = println("pinging server! I am alive!")

val funcFuture = Future{longFunc}
waiter(funcFuture,shortFunc,5 second)

val done = Await.result(funcFuture, 1 minutes)
相同但较短:

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

def longFunc = {Thread.sleep(30000); true}
def shortFunc = println("pinging server! I am alive!")

val funcFuture = Future{longFunc}

def ff:Future[_] = Future{
  shortFunc
  Try(Await.ready(funcFuture, 5 second)).getOrElse(ff)
}
ff

val done = Await.result(funcFuture, 1 minutes)

为什么不调用wait.result并超时5秒?如果这引发TimeoutException,则ping服务器并再次等待。次要详细信息:使用全局ExecutioContext不是一个好模式。