Added a timed actor to the project
This commit is contained in:
parent
799e9adcb9
commit
b0c7abc923
|
@ -25,6 +25,7 @@ public class AkkaMainSystem extends AbstractBehavior<AkkaMainSystem.Create> {
|
|||
private Behavior<Create> onCreate(Create command) {
|
||||
//#create-actors
|
||||
ActorRef<ExampleActor.Message> a = this.getContext().spawn(ExampleActor.create("Alice"), "alice");
|
||||
ActorRef<ExampleTimerActor.Message> b = this.getContext().spawn(ExampleTimerActor.create(), "timeractor");
|
||||
//#create-actors
|
||||
|
||||
a.tell(new ExampleActor.ExampleMessage(this.getContext().getSelf(),"Test123"));
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue