ScheduledThreadPoolExecutor scala

时间:2016-08-10 21:44:34

标签: java scala playframework

我正在尝试在scala play框架中实现Sceduled Job。

以下是我的代码:

def subCron = {

val task = new Runnable {
  def run() = {
    writingToFile(s"Name,Job,M,Age\n", "Media1", "FileName")
  }
}

val pool = new ScheduledThreadPoolExecutor(1)

val schedule = pool.scheduleWithFixedDelay(task, 0, 30, TimeUnit.SECONDS);
schedule.cancel(false)

}

基本思想是在特定时间间隔后写入文件。我在我的writingToFile中使用run函数,但似乎在调用函数时代码没有执行。

请建议如何使其发挥作用。

1 个答案:

答案 0 :(得分:0)

计划任务在定义后立即被取消,因此不会运行。

除此之外,Akka(已经附带Play)也支持调度任务。

import play.api.libs.concurrent.Execution.Implicits.defaultContext
// Delete a file after 10 seconds
val cancellable = system.scheduler.scheduleOnce(10.seconds) {
  file.delete()
}

// Print the message "Hi" every 30 seconds, starting after 5 seconds 
val cancellable = system.scheduler.schedule(5.seconds, 300.seconds) {
  log("Hi")
}

示例改编自:https://www.playframework.com/documentation/2.5.x/ScalaAkka#Scheduling-asynchronous-tasks