How to write a timer actor in Scala?

后端 未结 6 936
忘了有多久
忘了有多久 2020-12-20 12:30

I need an actor to send a message every minute. How do I best achieve this behaviour? I am afraid of using java.lang.Thread.sleep(long millis) as a thread can b

6条回答
  •  情歌与酒
    2020-12-20 13:33

    Since scala.actors is now deprecated and being replaced with akka actors (and since there is no react or receiveWithin in akka actors), here is how to do it using akka actors (it's actually less of a 'hack' than using receiveWithin anyways IMHO).

    The example below schedule a runnable to be invoked after 5 seconds:

    import akka.actor.{ActorSystem, Scheduler}
    import scala.concurrent.duration.FiniteDuration
    import scala.concurrent.ExecutionContext.Implicits.global
    
    class TimerExample {
    def example() = {
    
        def scheduler: Scheduler = ActorSystem.create("timer-example").scheduler
    
        val myRunnable = new Runnable {
          override def run(): Unit = {
            println("run invoked")
          }
        }
    
        println("scheduling...")
        scheduler.scheduleOnce(FiniteDuration(5,TimeUnit.SECONDS),myRunnable)
        Thread.sleep(6000)
        println("should have printed 'run invoked'")
    }
    

提交回复
热议问题