循环进入倒数计时器

马吉达里夫:

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

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. 发生倒计时时从timeDelay0开始倒数certainSomething
2. iShouldOnlyBeCalledWhenDelayHasBeenReached在倒数到0之前不要调用
。3.这都应该在一个循环内发生,服务器循环会准确地接收数据包。

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

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

注意:循环中还有其他功能。在做其他事情。这是主循环。我做不到Sleep

大卫·布德沃思(David Budworth):

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

这里有一个例子

它的另一个好处是,在select语句中,您可以具有其他用途的其他渠道。例如,如果您要在此循环中执行其他工作,则还可以在goroutine中生成该工作并将其发送回另一个通道。
然后,您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")
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章