Run a function periodically in Scala

前端 未结 4 557
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 07:01

I want to call an arbitrary function every n seconds. Basically I want something identical to SetInterval from Javascript. How can I achieve this i

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 07:32

    If you happen to be on Akka, Scheduler is quite convenient for this:

    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 scheduleOnce for one-off execution.

    The usual warnings about closing over mutable state apply.

提交回复
热议问题