timeutil

package
v0.23.2 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const DateFormat = "2006-01-02"

DateFormat is the time format used to display a date.

View Source
const FullTimeFormat = "2006-01-02 15:04:05.999999-07:00:00"

FullTimeFormat is the time format used to display any unknown timestamp type, and always shows the full time zone offset.

View Source
const LibPQTimePrefix = "0000-01-01"

LibPQTimePrefix is the prefix lib/pq prints time-type datatypes with.

View Source
const TimeWithTZFormat = "15:04:05.999999-07"

TimeWithTZFormat is the time format used to display a time with a time zone offset.

View Source
const TimeWithoutTZFormat = "15:04:05.999999"

TimeWithoutTZFormat is the time format used to display a time without a time zone offset.

View Source
const TimestampWithTZFormat = "2006-01-02 15:04:05.999999-07"

TimestampWithTZFormat is the time format used to display timestamps with a time zone offset. The minutes and seconds offsets are only added if they are non-zero.

View Source
const TimestampWithoutTZFormat = "2006-01-02 15:04:05.999999"

TimestampWithoutTZFormat is the time format used to display timestamps without a time zone offset. The minutes and seconds offsets are only added if they are non-zero.

Variables

View Source
var UnixEpoch = time.Unix(0, 0).UTC()

UnixEpoch represents the Unix epoch, January 1, 1970 UTC.

Functions

func FixedTimeZoneOffsetToLocation

func FixedTimeZoneOffsetToLocation(offset int, origRepr string) *time.Location

FixedTimeZoneOffsetToLocation creates a time.Location with an offset and a time zone string.

func FromUnixMicros

func FromUnixMicros(us int64) time.Time

FromUnixMicros returns the UTC time.Time corresponding to the given Unix time, usec microseconds since UnixEpoch. In Go's current time.Time implementation, all possible values for us can be represented as a time.Time.

func FromUnixNanos

func FromUnixNanos(ns int64) time.Time

FromUnixNanos returns the UTC time.Time corresponding to the given Unix time, ns nanoseconds since UnixEpoch. In Go's current time.Time implementation, all possible values for ns can be represented as a time.Time.

func LoadLocation

func LoadLocation(name string) (*time.Location, error)

LoadLocation returns the time.Location with the given name. The name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".

We do not use Go's time.LoadLocation() directly because it maps "Local" to the local time zone, whereas we want UTC.

func Now

func Now() time.Time

Now returns the current UTC time.

We've decided in times immemorial that always returning UTC is a good policy across the cluster so that all the timestamps print uniformly across different nodes, and also because we were afraid that timestamps leak into SQL Datums, and there the timestamp matters. Years later, it's not clear whether this was a good decision since it's forcing the nasty implementation below.

func NowNoMono

func NowNoMono() time.Time

NowNoMono is like Now(), but it strips down the monotonic part of the timestamp. This is useful for getting timestamps that rounds-trip through various channels that strip out the monotonic part - for example yaml marshaling.

func ParseTimeZoneOffset

func ParseTimeZoneOffset(
	location string, standard TimeZoneStringToLocationStandard,
) (offset int, origRepr string, success bool)

ParseTimeZoneOffset takes the string representation of a time.Location created by TimeZoneOffsetToLocation and parses it to the offset and the original representation specified by the user. The bool returned is true if parsing was successful. The offset is formatted <-%s>+%s or <+%s>+%s. A string with whitespace padding optionally followed by a (+/-) and a float should be able to be parsed. Example: " +10.5" is parsed in PG and displayed as <+10:06:36>-10:06:36.

func ReplaceLibPQTimePrefix

func ReplaceLibPQTimePrefix(s string) string

ReplaceLibPQTimePrefix replaces unparsable lib/pq dates used for timestamps (0000-01-01) with timestamps that can be parsed by date libraries.

func RunWithTimeout

func RunWithTimeout(
	ctx context.Context, op string, timeout time.Duration, fn func(ctx context.Context) error,
) error

RunWithTimeout runs a function with a timeout, the same way you'd do with context.WithTimeout. It improves the opaque error messages returned by WithTimeout by augmenting them with the op string that is passed in.

func Since

func Since(t time.Time) time.Duration

Since returns the time elapsed since t. It is shorthand for Now().Sub(t), but more efficient.

func StripMono

func StripMono(t time.Time) time.Time

StripMono returns a copy of t with its monotonic clock reading stripped. This is useful for getting a time.Time that compares == with another one that might not have the mono part. time.Time is meant to be compared with Time.Equal() (which ignores the mono), not with ==, but sometimes we have a time.Time in a bigger struct and we want to use require.Equal() or such.

func TimeZoneOffsetToLocation

func TimeZoneOffsetToLocation(offset int) *time.Location

TimeZoneOffsetToLocation takes an offset and name that can be marshaled by crdb between nodes and creates a time.Location. Note that the display time zone is always shown with ISO sign convention.

func TimeZoneStringToLocation

func TimeZoneStringToLocation(
	locStr string, std TimeZoneStringToLocationStandard,
) (*time.Location, error)

TimeZoneStringToLocation transforms a string into a time.Location. It supports the usual locations and also time zones with fixed offsets created by FixedTimeZoneOffsetToLocation().

func TimeZones

func TimeZones() []string

TimeZones lists all supported timezones.

func ToUnixMicros

func ToUnixMicros(t time.Time) int64

ToUnixMicros returns t as the number of microseconds elapsed since UnixEpoch. Fractional microseconds are rounded, half up, using time.Round. Similar to time.Time.UnixNano, the result is undefined if the Unix time in microseconds cannot be represented by an int64.

func Unix

func Unix(sec, nsec int64) time.Time

Unix wraps time.Unix ensuring that the result is in UTC instead of Local.

func Until

func Until(t time.Time) time.Duration

Until returns the duration until t. It is shorthand for t.Sub(Now()), but more efficient.

Types

type CPUStopWatch

type CPUStopWatch struct {
	// contains filtered or unexported fields
}

CPUStopWatch is a wrapper around cpuStopWatch that is safe to use concurrently. If CPUStopWatch is nil, all operations are no-ops and no locks are acquired.

func NewCPUStopWatch

func NewCPUStopWatch() *CPUStopWatch

NewCPUStopWatch returns a new CPUStopWatch if the grunning library is supported. Otherwise, it returns nil.

func (*CPUStopWatch) Elapsed

func (w *CPUStopWatch) Elapsed() time.Duration

Elapsed returns the total CPU time measured by the stop watch so far.

func (*CPUStopWatch) Start

func (w *CPUStopWatch) Start()

Start starts the CPU stop watch if it hasn't already been started.

func (*CPUStopWatch) Stop

func (w *CPUStopWatch) Stop()

Stop stops the CPU stop watch if it hasn't already been stopped and accumulates the CPU time that has been spent since it was started. If the CPU stop watch has already been stopped, it is a noop.

type DefaultTimeSource

type DefaultTimeSource struct{}

DefaultTimeSource is a TimeSource using the system clock.

func (DefaultTimeSource) NewTicker

func (DefaultTimeSource) NewTicker(duration time.Duration) TickerI

NewTicker creates a new ticker.

func (DefaultTimeSource) NewTimer

func (DefaultTimeSource) NewTimer() TimerI

NewTimer returns a TimerI wrapping *Timer.

func (DefaultTimeSource) Now

func (DefaultTimeSource) Now() time.Time

Now returns timeutil.Now().

func (DefaultTimeSource) Since

Since implements TimeSource interface

type ManualTime

type ManualTime struct {
	// contains filtered or unexported fields
}

ManualTime is a testing implementation of TimeSource.

func NewManualTime

func NewManualTime(initialTime time.Time) *ManualTime

NewManualTime constructs a new ManualTime.

func (*ManualTime) Advance

func (m *ManualTime) Advance(duration time.Duration)

Advance forwards the current time by the given duration.

func (*ManualTime) AdvanceTo

func (m *ManualTime) AdvanceTo(now time.Time)

AdvanceTo advances the current time to t. If t is earlier than the current time then AdvanceTo is a no-op.

func (*ManualTime) Backwards

func (m *ManualTime) Backwards(duration time.Duration)

Backwards moves the clock back by duration. Duration is expected to be positive, and it will be subtracted from the current time.

func (*ManualTime) MustAdvanceTo

func (m *ManualTime) MustAdvanceTo(now time.Time)

MustAdvanceTo is like AdvanceTo, except it panics if now is below m's current time.

func (*ManualTime) NewTicker

func (m *ManualTime) NewTicker(duration time.Duration) TickerI

NewTicker creates a new ticker.

func (*ManualTime) NewTimer

func (m *ManualTime) NewTimer() TimerI

NewTimer constructs a new timer.

func (*ManualTime) Now

func (m *ManualTime) Now() time.Time

Now returns the current time.

func (*ManualTime) Since

func (m *ManualTime) Since(t time.Time) time.Duration

Since implements TimeSource interface

func (*ManualTime) Timers

func (m *ManualTime) Timers() []time.Time

Timers returns a snapshot of the timestamps of the pending timers.

type StopWatch

type StopWatch struct {
	// contains filtered or unexported fields
}

StopWatch is a utility stop watch that can be safely started and stopped multiple times and can be used concurrently.

func NewStopWatch

func NewStopWatch() *StopWatch

NewStopWatch creates a new StopWatch.

func NewStopWatchWithCPU

func NewStopWatchWithCPU() *StopWatch

NewStopWatchWithCPU creates a new StopWatch that will track CPU usage in addition to wall-clock time.

func NewTestStopWatch

func NewTestStopWatch(timeSource func() time.Time) *StopWatch

NewTestStopWatch create a new StopWatch with the given time source. It is used for testing only.

func (*StopWatch) Elapsed

func (w *StopWatch) Elapsed() time.Duration

Elapsed returns the total time measured by the stop watch so far.

func (*StopWatch) ElapsedCPU

func (w *StopWatch) ElapsedCPU() time.Duration

ElapsedCPU returns the total CPU time measured by the stop watch so far. It returns zero if cpuStopWatch is nil (which is the case if NewStopWatchWithCPU was not called or the platform does not support grunning).

func (*StopWatch) LastStartedAt

func (w *StopWatch) LastStartedAt() (startedAt time.Time, started bool)

LastStartedAt returns the time the stopwatch was last started, and a bool indicating if the stopwatch is currently started.

func (*StopWatch) Start

func (w *StopWatch) Start()

Start starts the stop watch if it hasn't already been started.

func (*StopWatch) Stop

func (w *StopWatch) Stop()

Stop stops the stop watch if it hasn't already been stopped and accumulates the duration that elapsed since it was started. If the stop watch has already been stopped, it is a noop.

type TestTimeSource

type TestTimeSource struct {
	// contains filtered or unexported fields
}

TestTimeSource is a source of time that remembers when it was created (in terms of the real time) and returns the time based on its creation time and the number of "advances" it has had. It is used for testing only.

func NewTestTimeSource

func NewTestTimeSource() *TestTimeSource

NewTestTimeSource create a new TestTimeSource.

func (*TestTimeSource) Advance

func (t *TestTimeSource) Advance()

Advance advances the current time according to t by 1 nanosecond.

func (*TestTimeSource) Elapsed

func (t *TestTimeSource) Elapsed() time.Duration

Elapsed returns how much time has passed since t has been created. Note that it is equal to the number of advances in nanoseconds.

func (*TestTimeSource) Now

func (t *TestTimeSource) Now() time.Time

Now tells the current time according to t.

type TickerI

type TickerI interface {
	// Reset stops a ticker and resets its period to the specified duration. The
	// next tick will arrive after the new period elapses.
	Reset(duration time.Duration)

	// Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does
	// not close the channel, to prevent a concurrent goroutine reading from the
	// channel from seeing an erroneous "tick".
	Stop()

	// Ch returns the channel on which the ticks are delivered.
	Ch() <-chan time.Time
}

TickerI is an interface wrapping Ticker.

type TimeSource

type TimeSource interface {
	Now() time.Time
	Since(t time.Time) time.Duration
	NewTimer() TimerI
	NewTicker(duration time.Duration) TickerI
}

TimeSource is used to interact with clocks and timers. Generally exposed for testing.

type TimeZoneStringToLocationStandard

type TimeZoneStringToLocationStandard uint32

TimeZoneStringToLocationStandard is an option for the standard to use for parsing in TimeZoneStringToLocation.

const (
	// TimeZoneStringToLocationISO8601Standard parses int UTC offsets as *east* of
	// the GMT line, e.g. `-5` would be 'America/New_York' without daylight savings.
	TimeZoneStringToLocationISO8601Standard TimeZoneStringToLocationStandard = iota
	// TimeZoneStringToLocationPOSIXStandard parses int UTC offsets as *west* of the
	// GMT line, e.g. `+5` would be 'America/New_York' without daylight savings.
	TimeZoneStringToLocationPOSIXStandard
)

type TimeoutError

type TimeoutError struct {
	// contains filtered or unexported fields
}

TimeoutError is a wrapped ContextDeadlineExceeded error. It indicates that an operation didn't complete within its designated timeout.

func (*TimeoutError) Cause

func (t *TimeoutError) Cause() error

Cause implements Causer.

func (*TimeoutError) Error

func (t *TimeoutError) Error() string

func (*TimeoutError) Format

func (t *TimeoutError) Format(s fmt.State, verb rune)

Format implements fmt.Formatter.

func (*TimeoutError) Operation

func (t *TimeoutError) Operation() string

Operation returns the name of the operation that timed out.

func (*TimeoutError) SafeFormatError

func (t *TimeoutError) SafeFormatError(p errors.Printer) (next error)

SafeFormatError implements errors.SafeFormatter.

func (*TimeoutError) Temporary

func (*TimeoutError) Temporary() bool

Temporary implements net.Error.

func (*TimeoutError) Timeout

func (*TimeoutError) Timeout() bool

Timeout implements net.Error.

type Timer

type Timer struct {

	// C is a local "copy" of timer.C that can be used in a select case before
	// the timer has been initialized (via Reset).
	C    <-chan time.Time
	Read bool
	// contains filtered or unexported fields
}

The Timer type represents a single event. When the Timer expires, the current time will be sent on Timer.C.

This timer implementation is an abstraction around the standard library's time.Timer that provides a temporary workaround for the issue described in https://github.com/golang/go/issues/14038. As such, this timer should only be used when Reset is planned to be called continually in a loop. For this Reset pattern to work, Timer.Read must be set to true whenever a timestamp is read from the Timer.C channel. If Timer.Read is not set to true when the channel is read from, the next call to Timer.Reset will deadlock. This pattern looks something like:

var timer timeutil.Timer
defer timer.Stop()
for {
    timer.Reset(wait)
    select {
    case <-timer.C:
        timer.Read = true
        ...
    }
}

Note that unlike the standard library's Timer type, this Timer will not begin counting down until Reset is called for the first time, as there is no constructor function.

func NewTimer

func NewTimer() *Timer

NewTimer allocates a new timer.

func (*Timer) Reset

func (t *Timer) Reset(d time.Duration)

Reset changes the timer to expire after duration d and returns the new value of the timer. This method includes the fix proposed in https://github.com/golang/go/issues/11513#issuecomment-157062583, but requires users of Timer to set Timer.Read to true whenever they successfully read from the Timer's channel.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired, been stopped previously, or had never been initialized with a call to Timer.Reset. Stop does not close the channel, to prevent a read from succeeding incorrectly. Note that a Timer must never be used again after calls to Stop as the timer object will be put into an object pool for reuse.

type TimerI

type TimerI interface {

	// Reset will set the timer to notify on Ch() after duration.
	Reset(duration time.Duration)

	// Stop must only be called one time per timer.
	Stop() bool

	// Ch returns the channel which will be notified when the timer reaches its
	// time.
	Ch() <-chan time.Time

	// MarkRead should be called when a value is read from the Ch() channel.
	// If MarkRead is not called, the resetting the timer is less efficient.
	MarkRead()
}

TimerI is an interface wrapping Timer.

Directories

Path Synopsis
This binary takes the tzdata from Go's source and extracts all timezones names from them.
This binary takes the tzdata from Go's source and extracts all timezones names from them.
Package pgdate contains parsing functions and types for dates and times in a manner that is compatible with PostgreSQL.
Package pgdate contains parsing functions and types for dates and times in a manner that is compatible with PostgreSQL.

Jump to

Keyboard shortcuts

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