2016-04-12 56 views
0

如何在scala上实现count Timer? 所有我想定时器,计数10秒前继续在我的方法。在scala上实现倒数计时器

所有我发现是这样的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() 
    } 
} 
+0

如果你想要的只是延迟,请查看Thread.sleep。 – Aivean

回答

0

如果你想正确的无阻塞执行你的程序就必须构建特殊的方式来支持它。无论您使用阿卡scheduler

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

Future/Promise - 从未完成一个承诺,你有10秒的时间执行。

如果这是一个矫枉过正,你不介意阻止使用Thread.sleep(10000) - 你的线程将浪费那段时间。类似的阻断解决方案是:Scala - ScheduledFuture