scalaplayframeworkakkaplayframework-2.3

How to reference to the standard ActorSystem of play framework 2?


I wish to use the scheduler of akka, the examples are saying:

system.scheduler.scheduleOnce()

but there is no real information where the "system" should come from. The documentation is a little bit superficial and there was a lot of change (akka moved out of core scala).

If I write

val system = akka.actor.ActorSystem("system")

I will have a ActorSystem, but it will be a new independent ActorSystem with around 8 new threads. I think, that this is an overkill for a small scheduler and not really recommended.

How can I just re-use the existing system of play framework 2 ? Thanks


Solution

  • To get hands on the default actor system defined by Play you have to import the play.api.libs.concurrent.Akka helper.

    Akka.system will be a reference to the default actor system, and then you can do everything with it as you would do with an actor system created by yourself:

    import play.api.libs.concurrent.Akka
    
    val myActor = Akka.system.actorOf(Props[MyActor], name = "myactor")
    Akka.system.scheduler.scheduleOnce(...)
    

    update: The above static methods became deprecated in Play 2.5 and was removed in 2.6, so now you have to use dependency injection.

    In Scala:

    class MyComponent @Inject() (system: ActorSystem) {
    
    }
    

    In Java:

    public class MyComponent {
    
        private final ActorSystem system;
    
        @Inject
        public MyComponent(ActorSystem system) {
            this.system = system;
        }
    }