我目前有这段代码,试图计算触发某个条件所花费的时间。 (伪):

timeDelay = 900000 // time.Microsecond
for {
   // if a certain something happens, start a counting (time)
   if (certainSomething) {
      startTime = time.Now();

      if !prevTime.IsZero() {
        // add the time elapsed time to timeTick
        diffTime = time.Since(prevTime)
        timeTick = timeTick + diffTime
      }

      prevTime = startTime
   }

   if (timeTick < timeDelay) { // lessThan()
      // still has not reached target count (time elapsed)
      fmt.Println("Not Yet")
      // we dont want to get to the end of the loop yet
      continue
   }

   if (timeTick > timeDelay) { // greaterThan()
      // has finally reached the target count (time elapsed)
      fmt.Println("Yes! Finally")
      // yes the delay has been reached lets reset the time
      // and if `thisHappened` is triggered again, lets start counting again
      timeTick = time.Duration(0 * time.Microsecond)
   }

   // function shouldn't be called if the elapsed amount
   //      of time required has not yet been reached
   iShouldOnlyBeCalledWhenDelayHasBeenReached();
}

我也将这些用作辅助功能(实际代码)
func lessThan(diff time.Duration, upper int) bool {
    return diff < time.Duration(upper)*time.Microsecond && diff != 0
}

func greaterThan(diff time.Duration, upper int) bool {
    return diff > time.Duration(upper)*time.Microsecond
}

但是,我对自己的工作方式不满意。我不应该算数吧?我应该倒数...我只是感到困惑,需要在我应该使用哪种方法上获得帮助。

我想发生的事情:
1.当timeDelay发生时,从certainSomething倒数到0。
2.在倒数到0之前,请勿调用iShouldOnlyBeCalledWhenDelayHasBeenReached
3.这一切都应该在一个循环内发生,服务器循环会准确地接收数据包。

我的问题:
1.我应该怎么做才能实现这种倒计时风格?

谢谢您,任何建议或示例代码都会有很大帮助。

最佳答案

您可以设置一个 channel ,以在超出时间时通知您。

这是一个示例on play

它的另一个好处是,在select语句中,您可以具有其他用途的其他 channel 。例如,如果您要在此循环中执行其他工作,则还可以在goroutine中生成该工作并将其发送回另一个 channel 。
然后,您在timeDelay之后或其他工作完成时退出。

package main

import (
    "fmt"
    "time"
)

func main() {
    certainSomething := true // will cause time loop to repeat

    timeDelay := 900 * time.Millisecond // == 900000 * time.Microsecond

    var endTime <-chan time.Time // signal for when timer us up

    for {
        // if a certain something happens, start a timer
        if certainSomething && endTime == nil {
            endTime = time.After(timeDelay)
        }
        select {
        case <-endTime:
            fmt.Println("Yes Finally!")
            endTime = nil
        default:
            fmt.Println("not yet")
            time.Sleep(50 * time.Millisecond) // simulate work
            continue
        }

        // function shouldn't be called if the elapsed amount
        //      of time required has not yet been reached
        iShouldOnlyBeCalledWhenDelayHasBeenReached() // this could also just be moved to the <- endtime block above
    }
}

func iShouldOnlyBeCalledWhenDelayHasBeenReached() {
    fmt.Println("I've been called")
}

关于algorithm - 循环进入倒数计时器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36061263/

10-11 21:49