How to write a timer actor in Scala?

后端 未结 6 935
忘了有多久
忘了有多久 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

    I ended up in creation of dedicated Runnable instance, which keeps sending a message to the target actor. Like

    case class QueueTick()
    
    class QueueWatcherActor extends Actor {
    
      override def receive = {
        case QueueTick() => // do it here
      }
    
    }
    
    val ref = ActorSystem("xxx")
    
    val actor = ref.actorOf(Props[QueueWatcherActor])
    
    val executor = Executors.newSingleThreadScheduledExecutor()
    
    executor.scheduleAtFixedRate(new Runnable {
      def run() {
        actor ! QueueTick()
      }
    },1,60,TimeUnit.SECONDS)
    

提交回复
热议问题