I created a timer application to be run in a terminal window.
I'm witnessing some strange behavior in time.Time.Sub()
when I start a terminal timer and put my macOS laptop running it to sleep by closing it.
When I reopen the laptop, suddenly the function appears to not work properly, as tracked by this block of code, which can be seen in this copied output to miscalculate unless I am misunderstanding the time.Time
values:
== 615a Timer ==
20m59s
now: 2018-04-27 05:58:20.440440541 -0700 PDT m=+310.234277006
exactLeft: 20m59.142673336s
t.end: 2018-04-27 06:15:00.000129434 -0700 PDT m=+1569.376950342
t.end.Sub(now): 20m59.142673336s
Explicitly, now
is set to 5:58
and t.end
is set to 6:15
, which has a duration of 17m
. Yet, t.end.Sub(now)
evaluates to 21m
, which is a difference of about the time that my laptop was asleep. What is happening here?
The issue is caused I believe by the difference between wall clock and monotonic clock, both of which may or may not be held inside the Time
variables. Different methods on Time
variables give different results depending on presence or absence of monotonic clock. I'm not sure of all the ins and outs, and it changed in Go 1.9 I think, but it's documented at the top of the time package and in the godoc.
I think there may also be some differences dependent on how the specific OS treats monotonic clock. I suspect that the print statement is printing wall clock values but the Sub
method is using monotonic.
Try stripping monotonic clock from one of your Time variables using now = now.Round(0)
before calling Sub
. That should fix it by forcing it to use wall clock.