timex

package
v0.0.42 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2021 License: Apache-2.0 Imports: 2 Imported by: 0

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

type Ticker struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

A Ticker holds a channel that delivers 'ticks' of a clock at intervals, similar to time.Ticker from the standard library.

func NewTicker

func NewTicker(d time.Duration) *Ticker

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

func NewTickerWithContext(ctx context.Context, d time.Duration) *Ticker

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
        }
    }
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL