gpt4 book ai didi

algorithm - 进入循环倒数计时器

转载 作者:IT王子 更新时间:2023-10-29 02:27:44 25 4
gpt4 key购买 nike

我目前有这段代码试图计算触发特定条件的耗时。 (伪):

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

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

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

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

最佳答案

您可以设置一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com