死者在Kotlin的开关

我想在Kotlin实施一个死人的转换 。 在接收到最后一个MyEvent之后,它会触发一个TIME_INTERVAL秒的通知。 当收到一个新的MyEvent ,它重新启动定时器。

 private val stopWatch = object : () -> Unit { var timer = System.currentTimeMillis() var isRunning = false override fun invoke() { timer = System.currentTimeMillis() if (isRunning) return synchronized(this) { isRunning = true while (System.currentTimeMillis() - timer <= TIME_INTERVAL) {} fireNotification() isRunning = false } } } override fun onSomeEvent(e: MyEvent?) { runAsync(stopWatch) } 

通过使用kotlin.concurrent还是Java标准库,是否有更简单或更简单的方法来获得此功能?

如果我理解正确,你的代码在循环中不做任何事情,直到时间间隔已经过去。 这是一个坏主意,因为它消耗了大量的CPU,而不是等待。

我会使用ScheduledExecutr来安排通知的发射。 在通知被触发之前,当事件发生时,我会取消返回的未来:

 import java.time.Instant.now import java.util.concurrent.Executors import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit class StopWatch { private var future: ScheduledFuture<Void>? = null; private val executor = Executors.newSingleThreadScheduledExecutor() fun onSomeEvent() { synchronized(this) { future.let { future?.cancel(false) future = null } val command = { synchronized(this@StopWatch) { future = null } fireNotification() null } future = executor.schedule(command, 2, TimeUnit.SECONDS) } println("${now()} - event") } private fun fireNotification() { println("${now()} - notification") } fun shutdown() { executor.shutdown() } } fun main(args: Array<String>) { val stopWatch = StopWatch() stopWatch.onSomeEvent() Thread.sleep(1000) stopWatch.onSomeEvent() Thread.sleep(1000) stopWatch.onSomeEvent() Thread.sleep(1000) stopWatch.onSomeEvent() Thread.sleep(3000) stopWatch.onSomeEvent() stopWatch.shutdown() } 

打印:

 2017-05-07T12:45:55.647Z - event 2017-05-07T12:45:56.741Z - event 2017-05-07T12:45:57.743Z - event 2017-05-07T12:45:58.745Z - event 2017-05-07T12:46:00.747Z - notification 2017-05-07T12:46:01.750Z - event 2017-05-07T12:46:03.753Z - notification