Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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():
case <-tick.C:
if time.Now().Round(0).Sub(last) > sleptTime {
signalC <- struct{}{}
last = time.Now()
return signalC
Copy link

owulveryck commented Dec 12, 2020

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