Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a timer actor in Scala?

Tags:

scala

timer

actor

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 be shared among many actors in Scala, as far as I understand.

like image 342
Ivan Avatar asked Nov 07 '11 22:11

Ivan


4 Answers

You can use Akka FSM to model an actor that stays forMax millis in a waiting state and then sends a message, e.g. by switching to another state while using onTransition and staying there for 0 millis to switch back to waiting state. There is a good example at the akka page.

like image 56
Peter Schmitz Avatar answered Nov 05 '22 03:11

Peter Schmitz


Create an actor with receiveWithin to act as the timer.

like image 12
Daniel C. Sobral Avatar answered Nov 05 '22 03:11

Daniel C. Sobral


import scala.actors._
class Wakeup[A](millis: Int, who: ReplyReactor, alarm: A) extends Thread {
  val done = new java.util.concurrent.atomic.AtomicBoolean(false)
  override def run {
    while (!done.get()) {
      who ! alarm
      Thread.sleep(millis)
    }
  }
}
case object BEEP {}
val a = new ReplyReactor { def act { loop { react {
  case BEEP => println("Wha?!  "+new java.util.Date)
  case _ =>
}}}}
val b = new Wakeup(60000,a,BEEP)
a.start

Why use an actor when a thread is what you want?

scala> b.start

scala> Wha?!  Mon Nov 07 18:43:18 EST 2011
Wha?!  Mon Nov 07 18:44:18 EST 2011
Wha?!  Mon Nov 07 18:45:18 EST 2011
Wha?!  Mon Nov 07 18:46:18 EST 2011
Wha?!  Mon Nov 07 18:47:18 EST 2011
Wha?!  Mon Nov 07 18:48:18 EST 2011
Wha?!  Mon Nov 07 18:49:18 EST 2011
Wha?!  Mon Nov 07 18:50:18 EST 2011
Wha?!  Mon Nov 07 18:51:18 EST 2011
Wha?!  Mon Nov 07 18:52:18 EST 2011
like image 2
Rex Kerr Avatar answered Nov 05 '22 01:11

Rex Kerr


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)
like image 1
jdevelop Avatar answered Nov 05 '22 01:11

jdevelop