How to get time.Tick to tick immediately
If you want to check the job right away, don't use the ticker as the condition in the for loop. For example:
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
started := time.Now()
for {
job, err := client.Job(jobID)
if err == InternalError {
return err
}
if job.State == "running" {
break
}
now := <-ticker.C
if now.Sub(started) > 2*time.Minute {
return fmt.Errorf("timed out waiting for job")
}
}
If you do still need to check for DoesNotExistError
, you want to make sure you do it after the ticker so you don't have a busy-wait.
The actual implementation of Ticker
internally is pretty complicated. But you can wrap it with a goroutine:
func NewTicker(delay, repeat time.Duration) *time.Ticker {
ticker := time.NewTicker(repeat)
oc := ticker.C
nc := make(chan time.Time, 1)
go func() {
nc <- time.Now()
for tm := range oc {
nc <- tm
}
}()
ticker.C = nc
return ticker
}
ticker := time.NewTicker(period)
for ; true; <-ticker.C {
...
}
https://github.com/golang/go/issues/17601
Unfortunately, it seems that Go developers will not add such functionality in any foreseeable future, so we have to cope...
There are two common ways to use tickers:
for
loop
Given something like this:
ticker := time.NewTicker(period)
defer ticker.Stop()
for <- ticker.C {
...
}
Use:
ticker := time.NewTicker(period)
defer ticker.Stop()
for ; true; <- ticker.C {
...
}
for
-select
loop
Given something like this:
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
ticker := time.NewTicker(period)
defer ticker.Stop()
loop:
for {
select {
case <- ticker.C:
f()
case <- interrupt:
break loop
}
}
Use:
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
ticker := time.NewTicker(period)
defer ticker.Stop()
loop:
for {
f()
select {
case <- ticker.C:
continue
case <- interrupt:
break loop
}
}
Why not just use time.Tick()
?
While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".
https://golang.org/pkg/time/#Tick