Skip to content

Instantly share code, notes, and snippets.

@owulveryck
Created December 12, 2020 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owulveryck/f5478b614c0ee02881b946ab4d74d2e8 to your computer and use it in GitHub Desktop.
Save owulveryck/f5478b614c0ee02881b946ab4d74d2e8 to your computer and use it in GitHub Desktop.
Detect if the os has been in sleep mode by looking at the clock
func hasSlept(ctx context.Context, healthCheck time.Duration, sleptTime time.Duration) <-chan struct{} {
signalC := make(chan struct{})
go func(chan<- struct{}) {
tick := time.NewTicker(healthCheck)
last := time.Now()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if time.Now().Round(0).Sub(last) > sleptTime {
signalC <- struct{}{}
}
last = time.Now()
}
}
}(signalC)
return signalC
}
@owulveryck
Copy link
Author

time.Now().Round(0).Sub(last) is the important line here:

From the doc:

The canonical way to strip a monotonic clock reading is to use t = t.Round(0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment