Saturday, 26 May 2012

Akka 2 and setReceiveTimeout

The Akka documentation states that setReceiveTimeout is
"A timeout mechanism can be used to receive a message when no initial message is received within a certain time."
I was unsure about the "initial message" part and turns out that the underlying actor receives a timeout every time there hasn't been a message within the specified timeframe i.e. not just when no initial message has been received.

Small code sample to show the behaviour of setReceiveTimeout:

import java.util.Date
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.ReceiveTimeout
import akka.util.duration._
class MyActor extends Actor {
context.setReceiveTimeout(5 seconds)
def receive = {
case x: String => println(new Date + " / Recieved: " + x)
case ReceiveTimeout => println(new Date + " / No message received since 5 seconds")
}
}
object Main extends App {
val sys = ActorSystem("test")
val a = sys.actorOf(Props[MyActor])
println(new Date + " / Started")
Thread.sleep(15000) // expect two timeout messages, one after 5 seconds, next after 10
// send ten msg's (1 every second) just when we should receive the third timeout
1 to 10 foreach { x =>
a ! "Message: " + x
Thread.sleep(1000)
}
// the next timeout message should be received 5 seconds after the loop finishes
}

Output:


Sun May 27 13:23:57 EST 2012 / Started
Sun May 27 13:24:02 EST 2012 / No message received since 5 seconds
Sun May 27 13:24:07 EST 2012 / No message received since 5 seconds
Sun May 27 13:24:12 EST 2012 / Recieved: Message: 1
Sun May 27 13:24:13 EST 2012 / Recieved: Message: 2
Sun May 27 13:24:14 EST 2012 / Recieved: Message: 3
Sun May 27 13:24:15 EST 2012 / Recieved: Message: 4
Sun May 27 13:24:16 EST 2012 / Recieved: Message: 5
Sun May 27 13:24:17 EST 2012 / Recieved: Message: 6
Sun May 27 13:24:18 EST 2012 / Recieved: Message: 7
Sun May 27 13:24:19 EST 2012 / Recieved: Message: 8
Sun May 27 13:24:20 EST 2012 / Recieved: Message: 9
Sun May 27 13:24:21 EST 2012 / Recieved: Message: 10
Sun May 27 13:24:26 EST 2012 / No message received since 5 seconds
Sun May 27 13:24:31 EST 2012 / No message received since 5 seconds

No comments:

Post a Comment