From b0c7abc9230404a777c7ed5e2369cd0db3e757c7 Mon Sep 17 00:00:00 2001 From: Christoph Stahl Date: Tue, 9 May 2023 13:34:50 +0200 Subject: [PATCH] Added a timed actor to the project --- src/main/java/com/example/AkkaMainSystem.java | 1 + .../java/com/example/ExampleTimerActor.java | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/main/java/com/example/ExampleTimerActor.java diff --git a/src/main/java/com/example/AkkaMainSystem.java b/src/main/java/com/example/AkkaMainSystem.java index 7ddda70..868351b 100644 --- a/src/main/java/com/example/AkkaMainSystem.java +++ b/src/main/java/com/example/AkkaMainSystem.java @@ -25,6 +25,7 @@ public class AkkaMainSystem extends AbstractBehavior { private Behavior onCreate(Create command) { //#create-actors ActorRef a = this.getContext().spawn(ExampleActor.create("Alice"), "alice"); + ActorRef b = this.getContext().spawn(ExampleTimerActor.create(), "timeractor"); //#create-actors a.tell(new ExampleActor.ExampleMessage(this.getContext().getSelf(),"Test123")); diff --git a/src/main/java/com/example/ExampleTimerActor.java b/src/main/java/com/example/ExampleTimerActor.java new file mode 100644 index 0000000..0bffbea --- /dev/null +++ b/src/main/java/com/example/ExampleTimerActor.java @@ -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 { + + public interface Message {}; + + + public record ExampleMessage(String someString) implements Message { } + + public static Behavior create() { + return Behaviors.setup(context -> Behaviors.withTimers(timers -> new ExampleTimerActor(context, timers))); + } + + private final TimerScheduler timers; + + private ExampleTimerActor(ActorContext context, TimerScheduler timers) { + super(context); + this.timers = timers; + + Message msg = new ExampleMessage("test123"); + this.timers.startSingleTimer(msg, msg, Duration.ofSeconds(10)); + } + + @Override + public Receive createReceive() { + return newReceiveBuilder() + .onMessage(ExampleMessage.class, this::onExampleMessage) + .build(); + } + + private Behavior onExampleMessage(ExampleMessage msg) { + getContext().getLog().info("I have send myself this message after 10 Seconds: {}", msg.someString); + return this; + } +}