22

在 Scala 中延迟函数执行的最简单方法是什么,比如 JavaScript 的setTimeout?理想情况下,每次延迟执行(即顺序执行)都不会产生线程。我能找到的最接近的是 Akka 的Scheduler,但这太过分了。

出于测试目的,我打开了数千个连接,然后它们会在 10 秒内得到响应。在 node.js 中它看起来像:

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  setTimeout(function() {res.end('Hello World\n');}, 10000 );
}).listen(8080, '127.0.0.1');

但是,最接近的 Scala 版本是什么?我不在乎res.end是要在多个线程中执行还是在单个线程中排队。

4

1 回答 1

25

厌倦了因为过于简单地回答问题而受到抨击,以下是标准的 JVM 习语:

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
Type in expressions for evaluation. Or try :help.

scala> import java.util.{Timer,TimerTask}
import java.util.{Timer, TimerTask}

scala> val timer = new Timer
timer: java.util.Timer = java.util.Timer@2d9ffd6f

scala> def delay(f: () => Unit, n: Long) = timer.schedule(new TimerTask() { def run = f() }, n)
delay: (f: () => Unit, n: Long)Unit

scala> delay(() => println("Done"), 1000L)

scala> Done


scala> import java.util.concurrent._
import java.util.concurrent._

scala> val x = Executors.newScheduledThreadPool(2)
x: java.util.concurrent.ScheduledExecutorService = java.util.concurrent.ScheduledThreadPoolExecutor@2c5d529e

scala> x.schedule(new Callable[Int]() { def call = { println("Ran"); 42 }}, 1L, TimeUnit.SECONDS)
res3: java.util.concurrent.ScheduledFuture[Int] = java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@3ab0f534

scala> Ran

标准库中没有用于调度延迟任务的 API,但您可以制作一个ExecutionContext具有固定延迟的 API,以便使用 Scala Future

scala> import scala.concurrent._
import scala.concurrent._

scala> implicit val xx = new ExecutionContext() {
     | def reportFailure(t: Throwable) = t.printStackTrace()
     | def execute(r: Runnable) = x.schedule(new Callable[Unit]() { def call = r.run() }, 1L, TimeUnit.SECONDS)
     | }
xx: scala.concurrent.ExecutionContext = $anon$1@40d3ab8b

scala> Future(println("hello"))
res4: scala.concurrent.Future[Unit] = List()

scala> hello

scala> Future(42)
res5: scala.concurrent.Future[Int] = List()                

scala> .value
res6: Option[scala.util.Try[Int]] = Some(Success(42))

或者您可以使用 Akka 的调度程序,这是Scala 中 Scheduled Executor的规范答案

旧单线:

最简单的仍然只是future { blocking(Thread.sleep(10000L)); "done" }

但我想为我刚刚遇到的这个人做一个广告,它给你一个进度指标或中间值。我有点希望它有一个不同的名字,就是这样。

scala> import concurrent._
import concurrent._

scala> import ExecutionContext.Implicits._
import ExecutionContext.Implicits._

scala> import duration._
import duration._

scala> val deadline = 60.seconds.fromNow
deadline: scala.concurrent.duration.Deadline = Deadline(38794983852399 nanoseconds)

scala> new DelayedLazyVal(() => deadline.timeLeft.max(Duration.Zero), blocking {
     | Thread.sleep(deadline.timeLeft.toMillis)
     | Console println "Working!"
     | })
res9: scala.concurrent.DelayedLazyVal[scala.concurrent.duration.FiniteDuration] = scala.concurrent.DelayedLazyVal@50b56ef3

scala> res9()
res10: scala.concurrent.duration.FiniteDuration = 23137149130 nanoseconds

scala> res9.isDone
res11: Boolean = false

scala> res9()
res12: scala.concurrent.duration.FiniteDuration = 12499910694 nanoseconds

scala> res9()
res13: scala.concurrent.duration.FiniteDuration = 5232807506 nanoseconds

scala> Working!


scala> res9.isDone
res14: Boolean = true

scala> res9()
res15: scala.concurrent.duration.FiniteDuration = 0 days

这是使用 Either 的替代公式,用于计算延迟后的值。Left当然还有时间使用Left

scala> new DelayedLazyVal(()=> if (deadline.hasTimeLeft) Left(deadline.timeLeft) else
     | Right("Working!"), blocking(Thread.sleep(deadline.timeLeft.toMillis)))
res21: scala.concurrent.DelayedLazyVal[Product with Serializable with scala.util.Either[scala.concurrent.duration.FiniteDuration,String]] = scala.concurrent.DelayedLazyVal@78f9c6f2

scala> res21()
res22: Product with Serializable with scala.util.Either[scala.concurrent.duration.FiniteDuration,String] = Left(28553649064 nanoseconds)

scala> res21()
res23: Product with Serializable with scala.util.Either[scala.concurrent.duration.FiniteDuration,String] = Left(9378334087 nanoseconds)

scala> res21.isDone
res24: Boolean = false

scala> res21()
res25: Product with Serializable with scala.util.Either[scala.concurrent.duration.FiniteDuration,String] = Right(Working!)

scala> res21.isDone
res26: Boolean = true
于 2013-06-23T19:01:00.377 回答