2013-06-22 176 views
16

在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是要在多個線程中執行還是在單個線程中排隊。

+1

可能的複製,我不知道這樣的回答可以幫助:http://stackoverflow.com/a/16629357/1296806但也許如果你想要一個毫無價值一次性進行測試。 –

+0

你也可以看看這個其他問題:http://stackoverflow.com/questions/16359849/scala-scheduledfuture –

回答

20

厭倦了越來越高射炮回答的簡單問題太簡單,這裏有標準的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 = [email protected] 

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 = [email protected] 

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

scala> Ran 

沒有在標準庫調度延遲的任務沒有API,但你可以做的ExecutionContext具有固定的延遲,以便使用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 = [email protected] 

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)) 

或者你可以用阿卡的調度,這是在Scheduled Executor in Scala

老一班輪規範答案:

最簡單的仍然只是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] = [email protected] 

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 

下面是一個替代公式,用來計算延遲後的值。當然使用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]] = [email protected] 

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 
+6

不會導致成千上萬的線程睡10秒? –

+3

是否有非阻塞解決方案? –

+0

@OlegMikheev是的。 –