Documentation ¶
Overview ¶
Package timex provides stdlib time package related utilities.
It exports type Ticker which works like stdlib time.Ticker but closes its channel on stop.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Ticker ¶
A Ticker holds a channel that delivers 'ticks' of a clock at intervals, similar to time.Ticker from the standard library.
func NewTicker ¶
NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument, similar to standard library's time.Ticker.
NewTicker will panic if the duration is negative.
It differs from the standard library Ticker by closing C when Stop() is called, which allows for ranging over C:
for range ticker.C { // do something }
Example ¶
package main import ( "fmt" "time" "foxygo.at/s/timex" ) func main() { ticker := timex.NewTicker(20 * time.Millisecond) time.AfterFunc(50*time.Millisecond, ticker.Stop) cnt := 0 for range ticker.C { cnt++ } fmt.Println("cnt:", cnt) }
Output: cnt: 2
func NewTickerWithContext ¶
NewTickerWithContext creates a Ticker that stops when the context is cancelled.
Example ¶
package main import ( "context" "fmt" "time" "foxygo.at/s/timex" "golang.org/x/sync/errgroup" ) func main() { cnt := 0 f := func() error { cnt++ if cnt == 5 { return fmt.Errorf("five") } return nil } // errgroup.Group will cancel the context when one of the functions it // calls returns an error g, ctx := errgroup.WithContext(context.Background()) ticker := timex.NewTickerWithContext(ctx, 2*time.Millisecond) for range ticker.C { g.Go(f) } err := g.Wait() fmt.Println("cnt:", cnt, "err:", err) }
Output: cnt: 5 err: five
func (*Ticker) Stop ¶
func (t *Ticker) Stop()
Stop turns off the ticker, closing the ticker channel C, after which no more ticks will be sent. It is safe to call Stop more than once; subsequent calls to Stop do nothing.
When working with select avoid erroneous ticks on close with:
for { select { case _, ok := <-ticker.C: if ok { // do something } else { return } } }