开发者

Implement timeout in actors

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 autom开发者_运维技巧atically 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.


How about this?

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


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
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜