我正在尝试通过创建模块并注入Akka ActorSystem来安排Play框架中的某些定期工作。代码如下所示:
import akka.actor._
import javax.inject._
import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import play.api.Logger
class JobModule extends AbstractModule with AkkaGuiceSupport {
Logger info "Job module created"
def configure() = {
bind(classOf[Scheduler]).asEagerSingleton
}
}
object Scheduler
{
Logger info "Scheduler object created"
var ticker = 0
}
class Scheduler @Inject() (val system: ActorSystem)(implicit ec: ExecutionContext)
{
import Scheduler._
Logger info "Scheduler class created"
system.scheduler.schedule(0.seconds, 1.second) {
Logger debug s"tick $ticker"
ticker += 1
}
}
不幸的是,每次我使用内存H2数据库重新启动应用程序时,模块会在DB演变尝试之前创建两次,然后在应用演变之后创建。结果,我获得了相同“单例”对象和两个计划任务的两个实例。 在进化之前:
13 21:55:00.791 [info]application: Scheduler class created
13 21:55:00.798 [info]application: Scheduler object created
13 21:55:00.798 [debug]application: tick 0
13 21:55:00.869 [error]application:
! @7145bjbge - Internal server error, for (GET) [/] ->
并且在进化之后:
at play.api.db.evolutions.ApplicationEvolutionsProvider.get$lzycompute(EvolutionsModule.scala:53)
at play.api.db.evolutions.ApplicationEvolutionsProvider.get(EvolutionsModule.scala:53)
13 21:55:01.799 [debug]application: tick 1
13 21:55:02.810 [debug]application: tick 2
13 21:55:03.810 [debug]application: tick 3
13 21:55:04.810 [debug]application: tick 4
13 21:55:05.810 [debug]application: tick 5
13 21:55:05.975 [info]application: Job module created
13 21:55:06.025 [info]application: Creating Pool for datasource 'default'
13 21:55:06.026 [info]c.z.h.HikariDataSource: HikariPool-1 - is starting.
13 21:55:06.029 [info]p.a.d.DefaultDBApi: Database [default] connected at jdbc:h2:mem:bnitracker
13 21:55:06.061 [info]a.e.s.Slf4jLogger: Slf4jLogger started
13 21:55:06.064 [info]application: Scheduler class created
13 21:55:06.067 [info]application: Scheduler object created
13 21:55:06.067 [debug]application: tick 0
13 21:55:06.161 [info]play.api.Play: Application started (Dev)
13 21:55:06.810 [debug]application: tick 6
13 21:55:07.076 [debug]application: tick 1
13 21:55:07.810 [debug]application: tick 7