Sleeping actors?

前端 未结 4 1003
面向向阳花
面向向阳花 2021-01-31 20:44

What\'s the best way to have an actor sleep? I have actors set up as agents which want to maintain different parts of a database (including getting data from external sources).

4条回答
  •  醉梦人生
    2021-01-31 21:31

    There was a good point to Erlang in the first answer, but it seems disappeared. You can do the same Erlang-like trick with Scala actors easily. E.g. let's create a scheduler that does not use threads:

    import actors.{Actor,TIMEOUT}
    
    def scheduler(time: Long)(f: => Unit) = {
      def fixedRateLoop {
        Actor.reactWithin(time) {
          case TIMEOUT => f; fixedRateLoop
          case 'stop => 
        }
      }
      Actor.actor(fixedRateLoop)
    }
    

    And let's test it (I did it right in Scala REPL) using a test client actor:

    case class Ping(t: Long)
    
    import Actor._
    val test = actor { loop {
      receiveWithin(3000) {
        case Ping(t) => println(t/1000)
        case TIMEOUT => println("TIMEOUT")
        case 'stop => exit
      }
    } }
    

    Run the scheduler:

    import compat.Platform.currentTime
    val sched = scheduler(2000) { test ! Ping(currentTime) }
    

    and you will see something like this

    scala> 1249383399
    1249383401
    1249383403
    1249383405
    1249383407
    

    which means our scheduler sends a message every 2 seconds as expected. Let's stop the scheduler:

    sched ! 'stop
    

    the test client will begin to report timeouts:

    scala> TIMEOUT
    TIMEOUT
    TIMEOUT
    

    stop it as well:

    test ! 'stop
    

提交回复
热议问题