Added a timed actor to the project

This commit is contained in:
Christoph Stahl 2023-05-09 13:34:50 +02:00
parent 799e9adcb9
commit b0c7abc923
2 changed files with 46 additions and 0 deletions

View File

@ -25,6 +25,7 @@ public class AkkaMainSystem extends AbstractBehavior<AkkaMainSystem.Create> {
private Behavior<Create> onCreate(Create command) { private Behavior<Create> onCreate(Create command) {
//#create-actors //#create-actors
ActorRef<ExampleActor.Message> a = this.getContext().spawn(ExampleActor.create("Alice"), "alice"); ActorRef<ExampleActor.Message> a = this.getContext().spawn(ExampleActor.create("Alice"), "alice");
ActorRef<ExampleTimerActor.Message> b = this.getContext().spawn(ExampleTimerActor.create(), "timeractor");
//#create-actors //#create-actors
a.tell(new ExampleActor.ExampleMessage(this.getContext().getSelf(),"Test123")); a.tell(new ExampleActor.ExampleMessage(this.getContext().getSelf(),"Test123"));

View File

@ -0,0 +1,45 @@
package com.example;
import akka.actor.typed.javadsl.TimerScheduler;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
import java.time.Duration;
public class ExampleTimerActor extends AbstractBehavior<ExampleTimerActor.Message> {
public interface Message {};
public record ExampleMessage(String someString) implements Message { }
public static Behavior<Message> create() {
return Behaviors.setup(context -> Behaviors.withTimers(timers -> new ExampleTimerActor(context, timers)));
}
private final TimerScheduler<ExampleTimerActor.Message> timers;
private ExampleTimerActor(ActorContext<Message> context, TimerScheduler<ExampleTimerActor.Message> timers) {
super(context);
this.timers = timers;
Message msg = new ExampleMessage("test123");
this.timers.startSingleTimer(msg, msg, Duration.ofSeconds(10));
}
@Override
public Receive<Message> createReceive() {
return newReceiveBuilder()
.onMessage(ExampleMessage.class, this::onExampleMessage)
.build();
}
private Behavior<Message> onExampleMessage(ExampleMessage msg) {
getContext().getLog().info("I have send myself this message after 10 Seconds: {}", msg.someString);
return this;
}
}