How to write a timer actor in Scala?

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

    Or as @Daniel mentioned, here a running example:

    import scala.actors._
    import scala.actors.Actor._
    
    class TimerActor(val timeout: Long,val who: Actor,val reply: Any) extends Actor {
      def act {
        loop {
          reactWithin(timeout) {
            case TIMEOUT => who ! reply
          }
        }
      }
    }
    
    val a = actor {
      loop {
        react {
          case x => println(x)
        }
      }
    }
    
    val t = new TimerActor(1000, a, "Go for it")
    
    a.start
    t.start
    

提交回复
热议问题