【问题标题】:Implement count down timer on scala在 scala 上实现倒数计时器
【发布时间】:2016-04-12 17:20:42
【问题描述】:

如何在 scala 上实现 count dow Timer ? 我只想在继续我的方法之前倒计时 10 秒。

我发现的只有这个Stopwatch

包视图

class Stopwatch {
  var start = System.currentTimeMillis()
  def elapsed = System.currentTimeMillis() - start
  def printElapsed(msg: String) = {
    val delta = elapsed
    new Thread(new Runnable {
      def run = {
        System.out.println(msg + " time ellapsed: " + delta + "ms")
      }
    }).start()
  }
  def restart = {
    start = System.currentTimeMillis()
      new Thread(new Runnable {
      def run = {
        System.out.println("------restart------")
      }
    }).start()
  }
}

【问题讨论】:

  • 如果您只想延迟,请查看Thread.sleep

标签: scala timer


【解决方案1】:

如果您想要正确的非阻塞执行,您的程序必须以特殊方式构建以支持它。是否使用 Akka scheduler

system.scheduler.scheduleOnce(50 milliseconds) { 
  // call the rest of your method
}

Future/Promise - 一个永远不会完成的承诺,你会在 10 秒内执行它。

如果这太过分了,并且您不介意阻止使用 Thread.sleep(10000) - 您的线程将在这段时间内被浪费。类似的拦截解决方案是:Scala - ScheduledFuture

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-26
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多