简体   繁体   中英

How to define onStart method in scala play framework 2.4

how can i define startup job in play framework 2.4 with scala? play framework GlobalSetting I have already:

class StartupConfigurationModule extends AbstractModule{

  override def configure(): Unit = {
    Akka.system.scheduler.schedule(Duration(0,duration.HOURS),Duration(24,duration.HOURS))(Id3Service.start())
    Akka.system.dispatcher
  }

}

You need to register this in the modules.enabled of your application (in application.conf ).

It should schedule a call to start on the Id3Service after 0 hours and then every 24 hours.

The issue is that the module doesn't declare a dependency on a running application, or more interestingly on a started actorSystem. Guice can decide to start it before the app is initialized.

The follwing is one way to force the dependency on the initialized actorSystem (and reduce the footprint of your dependency)

import javax.inject.{ Singleton, Inject }

import akka.actor.ActorSystem
import com.google.inject.AbstractModule

import scala.concurrent.duration._

class StartupConfigurationModule extends AbstractModule {

  override def configure(): Unit = {
    bind(classOf[Schedule]).asEagerSingleton()
  }

}

@Singleton
class Schedule @Inject() (actorSystem: ActorSystem) {
  implicit val ec = actorSystem.dispatcher
  actorSystem.scheduler.schedule(Duration(0, HOURS), Duration(24, HOURS))(Id3Service.start())
}
object Id3Service {
  def start(): Unit = println("started")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM