Gal
Gal

Reputation: 5426

scala play: How to kill old actors / threads on automatic rebuild?

I have a play application where I am using actors that are do some constant work / monitoring.

e.g.

class MyActor extends Actor {
    def act() { while(true) { /* work */ } }
}

in my code I start this actor exactly once.
My problem is that whenever play automatically rebuilds the application (due to source changes), it will create a new Actor, but will not get rid of the old actor. The exact same thing happens if using threads (including daemon threads) instead of actors for the monitoring.

Is there any way to kill the old actors / threads on an automatic rebuild, or alternatively ensure that only a single actor will exist (I've tried making the actor thread an object, but this didn't help anything), other than restarting the application manually (I'm fine automatically with restarting the application on every change)?

Also, is there a better pattern for background monitoring in play (obviously one which will not create non-ending threads).

Thanks

Upvotes: 3

Views: 734

Answers (1)

Henrik Nordvik
Henrik Nordvik

Reputation: 330

You can define a Global object to listen to application events (Which must be defined in the default package):

import play.api.GlobalSettings

object Global extends GlobalSettings {

  override def onStart(application: play.api.Application) {
    println("Starting actors")
    MyActorSystem
  }

  override def onStop(application: play.api.Application) {
    println("Stopping actors")
    MyActorSystem.system.shutdown()
  }
}

The stop and start events are triggered when reload happens. If you are using Play's internal actor system I think you can use this instead:

play.api.libs.concurrent.Akka.system.shutdown()

Upvotes: 3

Related Questions