Timers

The Baker is more interesting. First of all, it needs a single Oven. We'll implement this by using a special behavior that we'll execute only once:

def turnOvenOn: Behavior[Command] = Behaviors.setup { context =>
val oven = context.spawn(Oven.empty, "Oven")
idle(oven)
}

Now, let's define the idle behavior that's just waiting for work:

def idle(oven: ActorRef[Oven.Command]): Behavior[Command] =
Behaviors.receivePartial {
case (context, BakeCookies(rawCookies, manager)) =>
oven ! Put(rawCookies.count, context.self)
Behaviors.withTimers { timers =>
timers.startSingleTimer(TimerKey, CheckOven, DefaultBakingTime)
baking(oven, manager)
}
}

Here, we expect a message from the manager telling us to bake cookies. Then, we use a new behavior constructor, withTimers, which gives us access to the TimerScheduler. With the scheduler, it is possible to define periodic and single timers that have been identified by some key. The definition of a new timer with the same key cancels the previously defined timer and also removes messages that have been sent by it, if they are still in the message box of the actor.

Here, we're using the timer as a kitchen clock to set up a single reminder to check the Oven after baking time passes. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.15.154