死人';Kotlin中的s开关

死人';Kotlin中的s开关,kotlin,Kotlin,我想在Kotlin中实现一个。这样做的目的是在收到最后一次MyEvent后的几秒钟内发出通知。当收到新的MyEvent时,它会重新启动计时器 private val stopWatch = object : () -> Unit { var timer = System.currentTimeMillis() var isRunning = false override fun invoke() { timer = System.currentTimeMillis()

我想在Kotlin中实现一个。这样做的目的是在收到最后一次MyEvent后的几秒钟内发出通知。当收到新的
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)
}
private val stopWatch=对象:()->单位{
var timer=System.currentTimeMillis()
var isRunning=false
重写函数调用(){
计时器=System.currentTimeMillis()
如果(正在运行)返回
已同步(此){
isRunning=true

while(System.currentTimeMillis()-timer如果我理解正确的话,您的代码包括在时间间隔结束之前不执行任何操作。这是一个坏主意,因为它会消耗大量的CPU,而不是等待

我将使用ScheduleXecutr来安排通知的触发。当事件在触发通知之前进入时,我将取消返回的未来:

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()
}

谢谢!空循环只是一个例子,也就是说,我可以很容易地睡眠。例如:
while(System.currentTimeMillis()-timer)
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