Hier ist ein grundlegendes Beispiel für eine geplante Actor-Implementierung.
Die Schauspieler Pläne einige regelmäßige Arbeit:
public class ScheduledActor extends AbstractActor {
// Protocol
private static final String CANCEL = "cancel";
private static final String TICK = "tick";
// The first polling in 30 sec after the start
private static final int TICK_INTERVAL_SEC = 90;
private static final int TICK_INTERVAL_SEC = 90;
private Cancellable scheduler;
public static Props props() {
return Props.create(ScheduledActor.class,()->new ScheduledActor());
}
public ScheduledActor() {
receive(ReceiveBuilder
.matchEquals(TICK, m -> onTick())
.matchEquals(CANCEL, this::cancelTick)
.matchAny(this::unhandled)
.build());
}
@Override
public void preStart() throws Exception {
getContext().system().scheduler().scheduleOnce(
Duration.create(ON_START_POLL_INTERVAL, TimeUnit.SECONDS),
self(),
TICK,
getContext().dispatcher(),
null);
}
@Override
public void postRestart(Throwable reason) throws Exception {
// No call to preStart
}
private void onTick() {
// do here the periodic stuff
...
getContext().system().scheduler().scheduleOnce(
Duration.create(TICK_INTERVAL_SEC, TimeUnit.SECONDS),
self(),
TICK,
getContext().dispatcher(),
null);
}
public void cancelTick(String string) {
if (scheduler != null) {
scheduler.cancel();
}
}
}
Der Schauspieler Life-Cycle-Handler erzeugt und Schauspieler und hebt es auf Antrag stop:
public class ScheduledActorMonitor {
private ActorRef scheduler;
private ActorSystem system;
@Inject
public ScheduledActorMonitor(ActorSystem system, ApplicationLifecycle lifeCycle) {
this.system = system;
initStopHook(lifeCycle);
}
public void startPolling() {
scheduler = system.actorOf(ScheduledActor.props();
}
public void cancelTick() {
if (scheduler != null) {
scheduler.tell(HelloScheduler.CANCEL, null);
}
}
private void initStopHook(ApplicationLifecycle lifeCycle) {
lifeCycle.addStopHook(() -> {
cancelTick();
return CompletableFuture.completedFuture(null);
});
}
}
Die StartupHandler als Singleton eingespritzt wird; er empfängt im Konstruktor einen Schauspieler Monitor und startet Polling:
@Singleton
public class StartupHandler {
@Inject
public StartupHandler(final ScheduledActorMonitor schedularMonitor) {
schedularMonitor.startPolling();
}
}
Die StartupHandler zur Injektion von Standardmodul Play-Modul registriert ist:
public class Module extends AbstractModule {
@Override
public void configure() {
bind(StartupHandler.class).asEagerSingleton();
}
}
Sie können mehr here lesen.
überprüfen Sie auch https://www.playframework.com/documentation/2.5.x/ScalaAkka#dependency-injecting-actors – LuisKarlos