Reputation: 287
According to the program from this link: Java Akka's ActorRef async issues
Is there any Akka native functions that I can use as a scheduling functions for actor.tell
? I want to schedule every time interval to auto "tell".
By the way, I do not choose Java's Executor as I do not want to waste OS resources.
Sample code attached:
ActorSystem as1 = ActorSystem.create("actor1");
ActorRef ar1 = as1.actorOf(Props.create(Hello.class), "ar1");
ActorRef ar2 = as1.actorOf(Props.create(Hello.class), "ar2");
Router router = new Router(new RoundRobinRoutingLogic());
router = router.addRoutee(ar1);
router = router.addRoutee(ar2);
System.out.println("Start to say hello!");
router.route("Bob",ActorRef.noSender());
router.route("John",ActorRef.noSender());
System.out.println("Finish to say hello!”);
Upvotes: 0
Views: 109
Reputation: 131
This section in the reference guide should be very helpful with this. From within an actor, you can do something like:
FiniteDuration delay = FiniteDuration.create(10, TimeUnit.MINUTES);
FiniteDuration initialDelay = FiniteDuration.create(2, TimeUnit.MINUTES);
getContext().system().scheduler().schedule(initialDelay, delay, self(), message, getContext().dispatcher(), ActorRef.noSender());
From outside an actor, you can do something like below if you have an ActorRef ref
FiniteDuration delay = FiniteDuration.create(10, TimeUnit.MINUTES);
FiniteDuration initialDelay = FiniteDuration.create(2, TimeUnit.MINUTES);
actorSystem.scheduler().schedule(initialDelay, delay, self(), message, actorSystem.dispatcher(), ActorRef.noSender())
Using a Router:
ActorSystem as1 = ActorSystem.create("actor1");
ActorRef ar1 = as1.actorOf(Props.create(Hello.class), "ar1");
ActorRef ar2 = as1.actorOf(Props.create(Hello.class), "ar2");
List<String> routees = Arrays.asList(ar1, ar2);
ActorRef routerActorRef = as1.actorOf(new RoundRobinGroup(routees).props(), "router");
System.out.println("Start to say hello!");
FiniteDuration delay = FiniteDuration.create(10, TimeUnit.MINUTES);
FiniteDuration initialDelay = FiniteDuration.create(2, TimeUnit.MINUTES);
as1.scheduler().schedule(initialDelay, delay, routerActorRef, "Bob", as1.dispatcher(), ActorRef.noSender())
as1.scheduler().schedule(initialDelay, delay, routerActorRef, "John", as1.dispatcher(), ActorRef.noSender())
System.out.println("Finish to say hello!”);
Upvotes: 1