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
.