From b535bbf27771f1488e4dde346c2cb47e4643b31e Mon Sep 17 00:00:00 2001 From: He-Pin Date: Thu, 13 Jun 2024 16:02:49 +0800 Subject: [PATCH] feat: Add UntypedAbstractActorWithTimers --- .../scala/org/apache/pekko/actor/Timers.scala | 14 +++++++++++ .../java/jdocs/testkit/TestKitDocTest.java | 24 ++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/actor/src/main/scala/org/apache/pekko/actor/Timers.scala b/actor/src/main/scala/org/apache/pekko/actor/Timers.scala index ee1f0413d4a..33649c45b19 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Timers.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Timers.scala @@ -83,6 +83,20 @@ abstract class AbstractActorWithTimers extends AbstractActor with Timers { final def getTimers: TimerScheduler = timers } +/** + * Java API: Support for scheduled `self` messages via [[TimerScheduler]]. + * + * Timers are bound to the lifecycle of the actor that owns it, + * and thus are cancelled automatically when it is restarted or stopped. + */ +abstract class UntypedAbstractActorWithTimers extends UntypedAbstractActor with Timers { + + /** + * Start and cancel timers via the enclosed `TimerScheduler`. + */ + final def getTimers: TimerScheduler = timers +} + /** * Support for scheduled `self` messages in an actor. * It is used by mixing in trait `Timers` in Scala or extending `AbstractActorWithTimers` diff --git a/docs/src/test/java/jdocs/testkit/TestKitDocTest.java b/docs/src/test/java/jdocs/testkit/TestKitDocTest.java index ffc4297fdec..e2750baa409 100644 --- a/docs/src/test/java/jdocs/testkit/TestKitDocTest.java +++ b/docs/src/test/java/jdocs/testkit/TestKitDocTest.java @@ -40,6 +40,7 @@ import org.apache.pekko.actor.Props; import org.apache.pekko.actor.Terminated; import org.apache.pekko.actor.AbstractActor; +import org.apache.pekko.actor.UntypedAbstractActorWithTimers; import org.apache.pekko.testkit.TestActor.AutoPilot; import java.util.List; @@ -92,7 +93,7 @@ public void demonstrateTestActorRef() { // #timer static class TestTimerActor extends AbstractActorWithTimers { - private static Object SCHED_KEY = "SchedKey"; + private static String SCHED_KEY = "SchedKey"; static final class TriggerScheduling {} @@ -107,6 +108,27 @@ void triggerScheduling() { getTimers().startSingleTimer(SCHED_KEY, new ScheduledMessage(), Duration.ofMillis(500)); } } + + static class TestTimerUntypedActor extends UntypedAbstractActorWithTimers { + private static String SCHED_KEY = "SchedKey"; + + static final class TriggerScheduling {} + + static final class ScheduledMessage {} + + @Override + public void onReceive(Object message) throws Throwable { + if (message instanceof TriggerScheduling) { + triggerScheduling(); + } else { + unhandled(message); + } + } + + void triggerScheduling() { + getTimers().startSingleTimer(SCHED_KEY, new ScheduledMessage(), Duration.ofMillis(500)); + } + } // #timer @Test