在Scala中定期运行函数

时间:2014-08-17 16:27:49

标签: scala intervals period

我想每n秒调用一个任意函数。基本上我想要一些与Javascript SetInterval相同的东西。我怎样才能在Scala中实现这一目标?

4 个答案:

答案 0 :(得分:42)

您可以使用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)

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

答案 1 :(得分:14)

如果您碰巧在Akka上,Scheduler非常方便:

@profile = Profile.find_by(user_id: params[:user_id])
@profile.update(profile_params)

还有val system = ActorSystem("mySystem", config) // ...now with system in current scope: import system.dispatcher system.scheduler.schedule(10 seconds, 1 seconds) { doSomeWork() } 一次性执行。

关于关闭可变状态的常见警告适用。

答案 2 :(得分:7)

它可以更具功能性,如



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

      }

    }

答案 3 :(得分:2)

Akka的更新,结合此处的“Hello World示例”:Lightbend Guides使用此处的说明:Scheduler

import scala.concurrent.duration._

howdyGreeter ! WhoToGreet("Akka")

val cancellable =
system.scheduler.schedule(
  0 seconds,
  1 seconds,
  howdyGreeter,
  Greet
)