src*_*091 33 scala period intervals
我想每秒调用一个任意函数n
.基本上我想SetInterval
从Javascript中获得相同的东西.我怎样才能在Scala中实现这一目标?
0__*_*0__ 49
你可以使用标准的东西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)
Run Code Online (Sandbox Code Playgroud)
或者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()
Run Code Online (Sandbox Code Playgroud)
dsk*_*rvk 18
如果您碰巧在Akka上,Scheduler非常方便:
val system = ActorSystem("mySystem", config)
// ...now with system in current scope:
import system.dispatcher
system.scheduler.schedule(10 seconds, 1 seconds) {
doSomeWork()
}
Run Code Online (Sandbox Code Playgroud)
还有scheduleOnce
一次性执行.
关于关闭可变状态的通常警告适用.
它可以更具功能性
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()
}
}
Run Code Online (Sandbox Code Playgroud)
更新 Akka,结合此处的“Hello World 示例”:Lightbend Guides using the instructions from here: Scheduler
import scala.concurrent.duration._
howdyGreeter ! WhoToGreet("Akka")
val cancellable =
system.scheduler.schedule(
0 seconds,
1 seconds,
howdyGreeter,
Greet
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18813 次 |
最近记录: |