How to make a "Clock" Akka Actor system in play framework 2.5.x?

426 views Asked by At

it just a question at solution. I success at create an actor repeating by a fixed time interval in Play Framework.But i want to make a actor that can be activity at a fixed time on date Eg: "12 hour".

My first solution is add a Calendar object in processor and check time whenever actor has been active. If time equal my setup time, just run my code. I think it is a possible solution but not good solution. Calendar object has been created many times and i want to reduce the number of Calendar object creates lowest at possible.

I has been find other solutions in origin Document: https://www.playframework.com/documentation/2.5.x/JavaAkka and other topics in S.O.F but not fit with me.

Any one can help me to solved it, please ?

1

There are 1 answers

1
Steve Chaloner On

Create a class that will set the schedule, using the actor system.

public class SchedulingTask {

    @Inject
    public SchedulingTask(final ActorSystem system,
                          @Named("foo-actor") ActorRef fooActor) {
        system.scheduler().schedule(
            Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay
            Duration.create(12, TimeUnit.HOURS),     //Frequency
            fooActor,
            "doSomething",
            system.dispatcher(),
            null);
    }
}

system is injected, and you can also inject a reference to the actor. Alternatively, you can look up the actor ref from system.

Once you've adapted this to do what you want, declare SchedulingTask in a module. Note that it is an eager singleton - this ensures it runs on start-up.

package com.example;
import com.google.inject.AbstractModule;
import play.libs.akka.AkkaGuiceSupport;

public class MyModule extends AbstractModule implements AkkaGuiceSupport {
    @Override
    protected void configure() {
        bindActor(FooActor.class, "foo-actor");
        bind(SchedulingTask.class).asEagerSingleton();
    }
}

Finally, update your application conf to enable the module.

play.modules.enabled += "com.example.MyModule"