Skip to content

Instantly share code, notes, and snippets.

@oluies
Forked from momania/gist:653276
Created October 29, 2010 18:41
Show Gist options
  • Save oluies/654110 to your computer and use it in GitHub Desktop.
Save oluies/654110 to your computer and use it in GitHub Desktop.
class HeartMonitor(millisUntilDeclaredDead: Long) extends Actor with FSM[Health, Long] {
import System.{currentTimeMillis => now}
val nextTest = 1000L
notifying {
case Transition(Stale, Alive) =>
log.info("HeartMonitor received initial heartbeat")
case Transition(Dead, Alive) =>
log.info("HeartMonitor noticed we are back alive again")
case Transition(_, Dead) =>
log.error("HeartMonitor thinks we are dead")
}
when(Stale) {
case Beat() => goto(Alive) using now until nextTest
case SkippedBeat() => stay until nextTest
case NoBeat() => goto(Dead)
}
when(Alive) {
case Beat() => stay using now until nextTest
case SkippedBeat() => stay until nextTest
case NoBeat() => goto(Dead)
}
when(Dead) {
case Beat() => goto(Alive) using now until nextTest
}
startWith(Stale, now, Some(nextTest))
object SkippedBeat {
def unapply(event: Event) = event match {
case Event(StateTimeout, lastHeartBeatTimeMillis) if !isDead(lastHeartBeatTimeMillis) => true
case _ => false
}
}
object NoBeat {
def unapply(event: Event) = event match {
case Event(StateTimeout, lastHeartBeatTimeMillis) if isDead(lastHeartBeatTimeMillis) => true
case _ => false
}
}
object Beat {
def unapply(event: Event) = event match {
case Event(heartBeat: HeartBeat, _) => true
case _ => false
}
}
def isDead(lastHeartBeatTimeMillis: Long): Boolean = {
now - lastHeartBeatTimeMillis > millisUntilDeclaredDead
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment