Last active
August 29, 2015 14:21
-
-
Save natemurthy/d294ab8794648266ed5f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import akka.actor._, concurrent.ExecutionContext.Implicits.global, concurrent.duration._ | |
| case object CreateChild | |
| case object GetChildren | |
| case object GetParent | |
| case class Message(str:String, forward:Boolean=false) | |
| class ChildActor extends Actor { | |
| def receive = { | |
| case msg: String => println(s"${context.self.path.name}: $msg") | |
| case GetParent => println(context.parent) | |
| } | |
| } | |
| class ParentActor extends Actor { | |
| var childCount = 0 | |
| def receive = { | |
| case CreateChild => | |
| context.actorOf(Props[ChildActor],name="child-"+childCount) | |
| childCount += 1 | |
| case GetChildren => println(context.children) | |
| case Message(str,fwd) => if (fwd) { context.children.foreach(_ forward str) } else println(str) | |
| } | |
| } | |
| val system = ActorSystem() | |
| val parent = system.actorOf(Props[ParentActor],"parent") | |
| for (i <- 0 to 4) { parent ! CreateChild } | |
| /* | |
| Using schedulers for repeated callbacks | |
| */ | |
| def startAsync: Unit = { | |
| system.scheduler.schedule(0.seconds,1.8.seconds){ parent ! Message("hello",true) } | |
| system.scheduler.schedule(1.seconds,1.2.seconds){ parent ! Message("bye",true) } | |
| system.scheduler.schedule(0.seconds,2.3.seconds){ parent ! Message("ok",true) } | |
| } | |
| class TaskActor extends Actor { | |
| var count = 5 | |
| override def preStart() = context.system.scheduler.scheduleOnce(1.second, self, "tick") | |
| def receive = { | |
| case "tick" => | |
| if (count == 0) { println("done") } | |
| else { | |
| context.system.scheduler.scheduleOnce(1.second, self, "tick") | |
| println(s"pending-$count") | |
| count -= 1 | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment