donglu3243 2016-03-17 12:58
浏览 46
已采纳

循环进入倒数计时器

I currently have this code that is trying to count the elapsed time to trigger a certain condition. (pseudo):

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

I'm also using these as helper functions (actual code)

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
}

But, I'm just not comfortable of how I'm doing it. I shouldn't be counting up, right? I should be counting down... I'm just confused and need help on what approach I should use.

What I want to happen:
1. A countdown from timeDelay to 0 starts when certainSomething happens.
2. Do not call iShouldOnlyBeCalledWhenDelayHasBeenReached until the countdown hits 0.
3. This should all happen inside a loop, a server loop receiving packets to be exact.

My question:
1. What should I do to achieve that countdown style?

Thank you, any suggestion or example code would help a lot.

Note: There are other functions in the loop. Doing other things. This is the main loop. I can't make it Sleep.

  • 写回答

4条回答 默认 最新

  • doumaoao0182 2016-03-17 13:39
    关注

    You can setup a channel to let you know when you've exceeded the time.

    Here's an example on play

    It has an added benefit that in the select statement, you can have other channels for other purposes. For example,if you are doing other work in this loop, you could also spawn that work in a goroutine and have it send the result back on another channel.
    Then you exit after timeDelay or when other work completes, or whatever.

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧