Skip to content

Commit

Permalink
feat: Add UntypedAbstractActorWithTimers (#1361)
Browse files Browse the repository at this point in the history
  • Loading branch information
He-Pin authored Jun 14, 2024
1 parent 7647f13 commit a9584ec
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
14 changes: 14 additions & 0 deletions actor/src/main/scala/org/apache/pekko/actor/Timers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
24 changes: 23 additions & 1 deletion docs/src/test/java/jdocs/testkit/TestKitDocTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {}

Expand All @@ -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
Expand Down

0 comments on commit a9584ec

Please sign in to comment.