在 Scala 中定期运行一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25351186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run a function periodically in Scala
提问by src091
I want to call an arbitrary function every nseconds. Basically I want something identical to SetIntervalfrom Javascript. How can I achieve this in Scala?
我想每秒调用一个任意函数n。基本上我想要一些与SetIntervalJavascript相同的东西。我怎样才能在 Scala 中实现这一点?
回答by 0__
You could use standard stuff from java.util.concurrent:
您可以使用以下标准的东西java.util.concurrent:
import java.util.concurrent._
val ex = new ScheduledThreadPoolExecutor(1)
val task = new Runnable {
def run() = println("Beep!")
}
val f = ex.scheduleAtFixedRate(task, 1, 1, TimeUnit.SECONDS)
f.cancel(false)
Or java.util.Timer:
或java.util.Timer:
val t = new java.util.Timer()
val task = new java.util.TimerTask {
def run() = println("Beep!")
}
t.schedule(task, 1000L, 1000L)
task.cancel()
回答by dskrvk
If you happen to be on Akka, Scheduleris quite convenient for this:
如果你碰巧在 Akka 上,Scheduler在这方面非常方便:
val system = ActorSystem("mySystem", config)
// ...now with system in current scope:
import system.dispatcher
system.scheduler.schedule(10 seconds, 1 seconds) {
doSomeWork()
}
There is also scheduleOncefor one-off execution.
还有scheduleOnce一次性执行。
The usual warnings about closing over mutable state apply.
关于关闭可变状态的常见警告适用。
回答by arunram
It can be more functional as in
它可以更实用,如
import java.util.TimerTask
import java.util.Timer
object TimerDemo {
implicit def function2TimerTask(f: () => Unit): TimerTask = {
return new TimerTask {
def run() = f()
}
}
def main(args : Array[String]) {
def timerTask() = println("Inside timer task")
val timer = new Timer()
timer.schedule(function2TimerTask(timerTask),100, 10)
Thread.sleep(5000)
timer.cancel()
}
}
回答by Jan Clemens Stoffregen
Update for Akka, in combination with the "Hello World example" from here: Lightbend Guidesusing the instructions from here: Scheduler
更新 Akka,结合此处的“Hello World 示例”:Lightbend Guidesusing the instructions from here: Scheduler
import scala.concurrent.duration._
howdyGreeter ! WhoToGreet("Akka")
val cancellable =
system.scheduler.schedule(
0 seconds,
1 seconds,
howdyGreeter,
Greet
)

