tags:

views:

57

answers:

2

Hi,

I am new to scala and actors. I need to implement such hypothetical situation: Server wait for messages, if it does not get any in say 10s period of time, it sends message to the Client. Otherwise it receives messages incoming. If it is inside processing some message and another message comes, it needs to be queued (I suppose that is done automatically by scala actors).

The second problem I am encountering is Sleeping. I need the actor to sleep for some constant period of time when it receives the message. But on the other hand I can't block, as I want incoming messages to be queued for further processing.

+1  A: 

Daniel has provided a better answer to the no-input condition part of the question. So I've edited out my inferior solution.

As to the delayed response part of the question, the message queue doesn't block while an actor sleeps. It can just sleep and messages will still accumulate.

However, if you want a fixed delay from when you receive a message to when you process it, you can, for example, create an actor that works immediately but wraps the message in a request for a delay:

case class Delay(when: Long, what: Any) { }

// Inside class DelayingActor(workingActor: Actor)
case msg => workingActor ! Delay(delayValue + System.currentTimeMillis , msg)

Then, the working actor would

case Delay(t,msg) =>
  val t0 = System.currentTimeMillis
  if (t>t0) Thread.sleep( t - t0 )
  msg match {
    // Handle message
  }
Rex Kerr
Thanks, that is what i was looking for.
tdi
+5  A: 

How about this?

loop {
  reactWithin(10000) {
    case TIMEOUT => // send message to client
    case work => // do work
  }
}
Daniel