Question

I have Play 2 app.

And code something like that. So, I run app in start mode and run mode.

val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 19)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)

val now = new Date()

val timeDifference = calendar.getTime.getTime - now.getTime

if (timeDifference >= 0) {
  val initialDelay = Duration.create(timeDifference, duration.MILLISECONDS)

  Akka.system.scheduler.scheduleOnce(initialDelay, new Runnable {
    override def run() {
      LOGGER.error(System.lineSeparator() +
        "=================================================" + System.lineSeparator() +
        "|   Forming and send report                     |" + System.lineSeparator() +
        "=================================================" + System.lineSeparator()
      )
    }
  })
}

Why scheduleOnce runs on shutdown?

Was it helpful?

Solution

The behavior you are seeing here actually effects all tasks scheduled in the default scheduler (LightArrayResolverScheduler) whether they were scheduled with schedule or scheduleOnce. If you look at the close method on LightArrayResolverScheduler, you will see this logic:

override def close(): Unit = Await.result(stop(), getShutdownTimeout) foreach {
  task =>
    try task.run() catch {
      case e: InterruptedException => throw e
      case _: SchedulerException   => // ignore terminated actors
      case NonFatal(e)             => log.error(e, "exception while executing timer task")
    }
}

So basically, it looks like during a shutdown of the timer that it will collect all outstanding tasks and execute them serially. I suppose this would not be a big deal if your scheduling was just sending messages to actors (as opposed to using a Runnable) as those actors would hopefully be terminated by this point and result in nothing happening (dead letters).

If you want to avoid this behavior, you could store the result of the call to scheduleOnce and explicitly cancel it first before you initiate your shutdown process.

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