golang time.Sleep bug?

20,535

Solution 1

Internally sleep is done with absolute time: if you call Sleep(n) at time T the program is scheduled not to wake up after n time, but at time T + n.

This is generally preferable because:

  • time usually does not flow backwards

  • due to OS scheduling delays a program which repeatedly sleeps may lag behind schedule indefinitely; using absolute time make it compensate for delays by sleeping for shorter intervals.

In your case, you just have to wait for a day for the program to start printing again. :D

Or set a time just a little in the past (say 15 sec), and see the program resuming after 15+2 sec.

PS. To clarify what happens with an example:

At 2016-08-25 16:27:12 the program calls time.Sleep(2 * time.Second) The Go runtime schedules the goroutine to be woken up on 2016-08-25 at 16:27:14 and puts the goroutine to sleep

meanwhile ...

the user sets the system time to 2016-08-24 16:27:13

now the timeout is scheduled to expire one day and one second later.

This should not happen on systems, on which Go uses POSIX CLOCK_MONOTONIC or equivalent thereof.

Solution 2

time.Sleep(20_000_000_000) n is nanoseconds

Share:
20,535
user2139281
Author by

user2139281

Updated on July 27, 2022

Comments

  • user2139281
    user2139281 almost 2 years

    I make test code below(gotest.go)

    package main
    
    import (
        "fmt"
        "time"
        "sync"
    )        
    
    func main() {
        var wg sync.WaitGroup
        wg.Add(1)
        go testa()    
    
        wg.Wait()
    }
    
    func testa() {
        for {
            fmt.Println("test goroutine")
            time.Sleep(2 * time.Second)
        }
    }
    

    console

    go run gotest.go
    

    and, change my computer's date (ex : 2015-07-30 -> 2015-07-29)

    and then, println not printed!!

    is it bug??

    (It is working to set next day)

    I use MacOs latest ver. Thank you.

    • RoninDev
      RoninDev over 8 years
      I have no such behaviour on windows machine. Maybe it's a bug on unix machines, cause for example using of time comparsion in time.Sleep function
  • Dmitry Frank
    Dmitry Frank over 7 years
    But this isn't true, or do I miss something? Here are docs for time.Sleep: ( golang.org/pkg/time/#Sleep ) Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately
  • Dmitry Frank
    Dmitry Frank over 7 years
    I verified and time.Sleep(1 * time.Second) indeed puts my goroutine to sleep for 1 second.
  • chill
    chill over 7 years
    This the time.Sleep interface; I said internally the interface is implemented with absolute timeout, see golang.org/src/runtime/time.go#L54
  • m4n0
    m4n0 over 2 years
    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review