Skip to content

Instantly share code, notes, and snippets.

@antoon-r
Created September 21, 2018 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoon-r/eae5c69715f49254dfbebcff23307577 to your computer and use it in GitHub Desktop.
Save antoon-r/eae5c69715f49254dfbebcff23307577 to your computer and use it in GitHub Desktop.
Akka does not unstash timer messages
import akka.actor.{ActorSystem, FSM, Props, Stash}
import scala.concurrent.duration.{FiniteDuration, _}
object Main
extends App
{
val system = ActorSystem("test")
system.actorOf(Props({new ExampleFSM}))
while(true){}
}
object ExampleFSM {
val interval: FiniteDuration = 2500 milliseconds
}
class ExampleFSM
extends FSM[ExState, ExData]
with Stash
{
startWith(ExState.Working, ExData.Empty)
override def preStart(): Unit = {
super.preStart()
self ! InternalMsg.Start
}
onTransition {
case _ -> ExState.Working =>
println("Transition to [%s] state.".format(ExState.Working))
unstashAll()
case _ -> ExState.Writing =>
println("Transition to [%s] state.".format(ExState.Writing))
setTimer("start", InternalMsg.Start, ExampleFSM.interval, repeat = false)
}
whenUnhandled {
case Event(msg, _) =>
if (stateName != ExState.Working) {
println(s"################################# Stashing $msg")
stash()
} else {
println("Unhandled message detected: " + msg)
}
stay()
}
when(ExState.Working) {
case Event(m@InternalMsg.Start, _) =>
println(s"Received $m")
self ! InternalMsg.BeginWriting
goto(ExState.Writing)
}
when(ExState.Writing) {
case Event(m@InternalMsg.BeginWriting, _) =>
println(s"Received $m")
self ! InternalMsg.Work(50)
stay()
case Event(m@InternalMsg.Work(count), _) =>
println(s"Received $m")
Thread.sleep(100)
if (count == 0) {
goto(ExState.Working)
} else {
self ! InternalMsg.Work(count - 1)
stay()
}
}
}
private object InternalMsg {
case object Start
case object BeginWriting
case class Work(value: Int)
}
trait ExState
object ExState {
case object Working extends ExState
case object Writing extends ExState
case object Done extends ExState
}
trait ExData
object ExData {
case object Empty extends ExData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment