Java Akka 的 ActorRef 异步与预定问题

Java Akka's ActorRef async with scheduled issues

根据此 link 中的程序:

是否有任何 Akka 本机函数可用作 actor.tell 的调度函数?我想安排每个时间间隔自动 "tell".

顺便说一句,我不选择Java的Executor,因为我不想浪费OS资源。

附上示例代码:

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!”);

这个 section in the reference guide 应该对此很有帮助。 在 actor 中,您可以执行以下操作:

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());

如果你有一个 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())

使用路由器:

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!”);