Question

I'm attempting to schedule an Akka job when my Play 2.2 application starts.

In it's simplest form, this is what my code looks like:

import play.api.Application
import play.api.Play.current
import play.api.GlobalSettings
import play.api.Logger
import play.api.db.DB
import scala.concurrent.duration._

import play.api.libs.concurrent.Akka
import play.api.libs.concurrent.Execution.Implicits._

import scala.slick.driver.MySQLDriver.simple._

object Global extends GlobalSettings {
  override def onStart(app: Application) {
    lazy val database = Database.forDataSource(DB.getDataSource())

    scheduleTheThing(app)
  }

  private def scheduleTheThing(app: Application) {
    Akka.system.scheduler.scheduleOnce(1.minute, new Runnable {
      override def run() {
        Logger.info("running the thing!")
        controllers.Application.runTheThing
      }
    })
  }
}

As you can see, I'm creating a new Runnable that will be executed 1 minute after the application starts. Logger.info("Running the thing!") gets executed just fine... I'm able to see "Running the thing!" in the application log 1 minute after starting the server. However, controllers.Application.runTheThing doesn't seem to get called:

object Application extends Controller {
  def runTheThing = DBAction {
    implicit session => {
      Logger.info("It's happening!")
      DBThing.doSomeDBStuff()
    }
  }
  // ...
}

My "It's happening!" log statement never shows up, and the stuff that DBThing.doSomeDBStuff() is supposed to do never happens. The curious thing is that there are no errors in the console or log files.

How is one supposed to call a controller DBAction from a scheduled runnable? Or How should I rework my scheduler so that this works? Any help would be greatly appreciated, thanks.

Was it helpful?

Solution

Calling the action method will do nothing but return an instance of Action, to actually execute it you would have to call it like play normally does with a request. I would recommend to extract this to non-controller code and call that from your scheduled task instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top