ptime

package
v0.4.170 Latest Latest
Warning

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

Go to latest
Published: May 11, 2024 License: ISC Imports: 10 Imported by: 4

Documentation

Overview

Package parltime provides on-time timers, 64-bit epoch, formaatting and other time functions.

Index

Constants

View Source
const (
	Date6 = "060102"
)
View Source
const (
	FractionScale = uint64(1) << 63
)
View Source
const (

	// RFC3339NanoSpace RFC3339 format, ns precision, space separator
	RFC3339NanoSpace string = "2006-01-02 15:04:05.999999999Z07:00"
)

Variables

This section is empty.

Functions

func Date added in v0.4.12

func Date(year int, month int, day int, hour int, min int, sec int, nsec int, loc *time.Location) (t time.Time, valid bool)

ptime.Date is like time.Date with a flag valid that indicates whether the provided values represents a valid date. year is a 4-digit year, ie. 2022 is 2022. month 1–12, day 1–31, hour 0–23 minute 0-59, sec 0–59

func Date1k added in v0.4.12

func Date1k(year int, month int, day int, hour int, min int, sec int, nsec int, loc *time.Location) (t time.Time, valid bool)

ptime.Date is like time.Date with a flag valid that indicates whether the provided values represents a valid date. year is a 4-digit year, ie. 2022 is 2022. month 1–12, day 1–31, hour 0–23 minute 0-59, sec 0–59 A year below 1000 is not considered valid

func Duration added in v0.4.26

func Duration(d time.Duration) (printableDuration string)

Duration formats time.Duration to string with 2 digits precision or better.

  • Duration is more readable than time.Duration.String() that has full ns precision.
  • max precision is ns for < 10 µs
  • min precision is day for >= 10 days
  • units: ns µs ms s m h d “17h27m”
  • subsecond digits are rounded with halfway-value rounded away from zero
  • second and larger values is truncate

func Duro

func Duro(period time.Duration, atTime time.Time) (d time.Duration)

Duro returns the duration in nanoseconds until the next duration-multiple from zero time.

  • The period starts from atTime
  • time zone for multiple-calculation is defined by atTime, often time.Local
  • time zone matters for 24 h or longer durations

func GetTimeString

func GetTimeString(wallTime *time.Time) (s string)

GetTimeString rfc 3339: email time format 2020-12-04 20:20:17-08:00

func Ms

func Ms(d time.Duration) string

Ms gets duration in milliseconds

func Ns

func Ns(t time.Time) string

Ns converts time to string with nanosecond accuracy and UTC location

func NsLocal

func NsLocal(t time.Time) string

NsLocal converts time to string with nanosecond accuracy and local time zone

func OnTickerThread added in v0.4.101

func OnTickerThread(callback func(at time.Time), period time.Duration, loc *time.Location, g Go)

OnTickerThread is a goroutine that invokes a callback periodically

  • period must be greater than zero or panic
  • loc is optional time zone, default time.Local, other time zone is time.UTC
  • — time zone matters for periods longer than 1 hour or time-zone offiset minutes
  • g can be nil, in which panics are echoed to standard error. The thread is then not awaitable or cancelable
  • OnTickerThread is a time.Ticker using on-period multiples that invokes a callback periodically without further action
  • OnTickerThread eliminates channel receive actions at the cost of an additional OnTickerThread thread
  • a thread-less on-period ticker is OnTicker

func OnTimer

func OnTimer(period time.Duration, t ...time.Time) (timer *time.Timer)

OnTimer returns a time.Timer that waits until the next period-multiple since zero time.

  • default starting time until the period multiple is now: time.Now(), optionally the absolute time t
  • t contains time zone that matters for periods over 1 hour, typically this is time.Local
  • the other time zone for Go is time.UTC
  • period must be greater than zero or panic
  • time.NewTimer does not offer the period calculation

func ParseNs

func ParseNs(timeString string) (t time.Time, err error)

ParseNs parses an RFC3339 time string with nanosecond accuracy

func ParseRfc3339nsz added in v0.4.12

func ParseRfc3339nsz(timeString string) (t time.Time, err error)

ParseRfc3339nsz parses a UTC time string at nanoseconds precision.

"2022-01-01T08:00:00.000000000Z"

func ParseS

func ParseS(timeString string) (t time.Time, err error)

ParseS parses an RFC3339 time string with nanosecond accuracy

func ParseTime

func ParseTime(dateString string) (tm time.Time, err error)

ParseTime parses output from Rfc3339

func Rfc3339

func Rfc3339(t time.Time) string

Rfc3339 converts local time to string with second precision and time offset: 2006-01-02 15:04:05-07:00

func Rfc3339msz added in v0.4.12

func Rfc3339msz(t time.Time) (s string)

Rfc3339msz prints a time using UTC and milliseconds precision.

"2022-01-01T08:00:00.000Z"

func Rfc3339nsz added in v0.4.12

func Rfc3339nsz(t time.Time) (s string)

Rfc3339nsz prints a time using UTC and nanoseconds precision.

"2022-01-01T08:00:00.000000000Z"

func Rfc3339sz added in v0.4.12

func Rfc3339sz(t time.Time) (s string)

Rfc3339sz prints a time using UTC and seconds precision.

"2022-01-01T08:00:00Z"

func Rfc3339usz added in v0.4.12

func Rfc3339usz(t time.Time) (s string)

Rfc3339usz prints a time using UTC and microseconds precision.

"2022-01-01T08:00:00.000000Z"

func S

func S(t time.Time) string

S converts time to string with second accuracy and UTC location

func SGreater

func SGreater(t1 time.Time, t2 time.Time) bool

SGreater compares two times first rouding to second

Types

type Alert

type Alert struct {
	time.Duration
	// Timer.C can be awaited for any trigging of the timer
	//	- Timer.C never closes and only sends a single value on trig
	//	- Timer is reinitialized on each Start invocation
	*time.Timer
	// Fired may be set to true by consumer on Timer.C trig
	//	- doing so saves a [time.Timer.Stop] invocation on next [Alert.Stop]
	// true if the timer trigged after the last Start invocation prior to any Stop invocation
	Fired bool
}

Alert impelments a renewable alert timer. not thread-safe

func NewAlert

func NewAlert(d time.Duration) (al *Alert)

NewAlert allocates a renewable alert time of specific duration

  • Alert.Start initializes a new period regardless of state
  • Alert.Stop releases resources regardless of state. Alert.Stop is idempotent
  • if Alert.Start was invoked, a subsequent Alert.Stop is required to release resources
  • after Start, [Alert.Timer.C] can be awaited for any trigging of the timer
  • [Alert.Timer.C] never closes and only sends a single value on trig
  • [Alert.Fired] is true if Start was invoked and the timer trigged prior to Stop

func (*Alert) Start

func (al *Alert) Start()

Start initializes a new alert period

  • can be invoked at any time. Not thread-safe

func (*Alert) Stop

func (al *Alert) Stop()

Stop releases resources associated with this alert

  • idempotent, can be invoked at any time. Not thread-safe

type AverageInterval added in v0.4.48

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

AverageInterval is a container for the datapoint aggregate over a single period

func NewAverageInterval added in v0.4.48

func NewAverageInterval(index PeriodIndex) (ai *AverageInterval)

NewAverageInterval returns an avareging container for one averaging interval

func (*AverageInterval) Add added in v0.4.48

func (a *AverageInterval) Add(value float64)

Add adds a datapoint to the averager

  • count of values incremented
  • value added to total

func (*AverageInterval) Aggregate added in v0.4.48

func (a *AverageInterval) Aggregate(countp *uint64, floatp *float64)

Aggregate provides averaging content for calculating the average

func (*AverageInterval) Index added in v0.4.106

func (a *AverageInterval) Index() (index PeriodIndex)

type Averager added in v0.4.48

type Averager[T constraints.Integer] struct {
	// contains filtered or unexported fields
}

Averager is a container for averaging integer values providing perioding and history.

  • maxCount is the maximum interval over which average is calculated
  • average is the average value of provided datapoints during all periods
  • because averaging is over 10 or many periods, the average will change slowly

func NewAverager added in v0.4.48

func NewAverager[T constraints.Integer]() (averager *Averager[T])

NewAverager returns an object that calculates average over a number of interval periods.

  • interval-length is 1 s
  • averaging over 10 intervals

func NewAverager2 added in v0.4.51

func NewAverager2[T constraints.Integer](period time.Duration, periodCount int) (averager *Averager[T])

NewAverager2 returns an object that calculates average over a number of interval periods.

  • period 0 means default 1 s interval-length
  • periodCount 0 means averaging over 10 intervals

func (*Averager[T]) Add added in v0.4.48

func (a *Averager[T]) Add(value T, t ...time.Time)

Add adds a new value basis for averaging

  • value is the sample value
  • t is the sample time, default time.Now()

func (*Averager[T]) Average added in v0.4.48

func (a *Averager[T]) Average(t ...time.Time) (average float64, count uint64)

Average returns the average

  • t is time, default time.Now()
  • if sample count aggregated across the slice zero, average is zero
  • count is number of values making up the average

type Averager3 added in v0.4.48

type Averager3[T constraints.Integer] struct {
	Averager[T]
	// contains filtered or unexported fields
}

Averager3 is an average container with last, average and max values.

func NewAverager3 added in v0.4.48

func NewAverager3[T constraints.Integer]() (averager *Averager3[T])

NewAverager3 returns an calculator for last, average and max values.

func (*Averager3[T]) Add added in v0.4.48

func (av *Averager3[T]) Add(value T, t ...time.Time)

Add updates last, average and max values

func (*Averager3[T]) Status added in v0.4.48

func (av *Averager3[T]) Status() (s string)

Status returns "[last]/[average]/[max]"

  • if no values at all: "-/-/-"
  • if no values avaiable to calculate average "1s/-/10s"

type ClosingTicker

type ClosingTicker struct {
	C                 <-chan time.Time
	MaxDuration       time.Duration // atomic int64
	perrors.ParlError               // panic in Shutdown or panic in tick thread
	// contains filtered or unexported fields
}

ClosingTicker is like time.Ticker but the channel C closes on shutdown. A closing channel is detectable by listening threads. If the computer is busy swapping, ticks will be lost. MaxDuration indicates the longest time observed between ticks. MaxDuration is normally 1 s

func NewClosingTicker

func NewClosingTicker(d time.Duration) (t *ClosingTicker)

NewClosingTicker returns a Ticker whose channel C closes on shutdown. A closing channel is detectable by a listening thread.

func (*ClosingTicker) GetError

func (t *ClosingTicker) GetError() (maxDuration time.Duration, err error)

func (*ClosingTicker) Shutdown

func (t *ClosingTicker) Shutdown()

Shutdown causes the channel C to close and resources to be released

type Epoch added in v0.4.50

type Epoch time.Duration

Epoch translates a time value to a 64-bit value that can be used atomically.

func EpochNow added in v0.4.50

func EpochNow(t ...time.Time) (epoch Epoch)

EpochNow translates a time value to a 64-bit value that can be used atomically.

func (Epoch) IsValid added in v0.4.50

func (epoch Epoch) IsValid() (isValid bool)

IsValid returns true if epoch is not zero-time, ie. Epoch(0) corredsponding to time.TIME{} and Time.IsZero

func (Epoch) Time added in v0.4.50

func (epoch Epoch) Time() (t time.Time)

Time returns the time.Time value corresponding to epoch

type EpochValue added in v0.4.50

type EpochValue Epoch

EpochValue is a timestamp with Thread-Safe atomic access.

func (*EpochValue) Get added in v0.4.50

func (ev *EpochValue) Get() (epoch Epoch)

Get returns the current Epoch value

  • zero epoch is returned as zero-time Time.IsZero, time.Time{}
  • to get time.Time: epochValue.Get().Time()
  • to check if non-zero: epochValue.Get().IsValid()

func (*EpochValue) Set added in v0.4.50

func (ev *EpochValue) Set(epoch Epoch) (oldEpoch Epoch)

Set updates the Epoch value returning the old value

  • 0 is the zero-value

func (*EpochValue) SetTime added in v0.4.50

func (ev *EpochValue) SetTime(t ...time.Time) (oldEpoch Epoch)

SetTime updates the Epoch value to a time.Time value returning the old Epoch value

  • default time value is time.Now()
  • time.IsZero or time.Time{} is the zero-value

type Go added in v0.4.58

type Go interface {
	Done(err *error)
	Context() (ctx context.Context)
}

type InvokeOnTimer added in v0.4.126

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

InvokeOnTimer implements a timeout action

func NewInvokeOnTimer added in v0.4.126

func NewInvokeOnTimer(d time.Duration, errPanic error, elapsedFunc func(), errCh ...chan<- error) (timer *InvokeOnTimer)

NewInvokeOnTimer panics or invokes elapsedFunc if not reset within d

  • default d 100 ms
  • on timer expiry:
  • — if errPanic is non-nil, process-terminating panic
  • — if elapsedFunc is non-nil, it is invoked. Panics in elapsedFunc are recovered
  • errPanic and elapsedFunc cannot both be nil
  • each NewInvokeOnTimer launches a separate, blocked thread
  • if errCh is present it should be a buffered channel receving a value on thread-exit that may be a panic from the thread. the thread should not have any panics but a panic may occur in elapsedFunc.
  • if errCh is missing or nil, panic is echoed to stderr
  • resources are released on:
  • — Stop invocation
  • — timer firing

func (*InvokeOnTimer) Stop added in v0.4.126

func (t *InvokeOnTimer) Stop()

Stop cancels the timer and releases resources

type OnTicker added in v0.4.58

type OnTicker struct {
	C <-chan time.Time // The channel on which the ticks are delivered.
	// contains filtered or unexported fields
}

OnTicker is a ticker triggering on period-multiples since zero time

  • time.Ticker has a C field and Stop and Reset methods
  • onTickerThread is launched in the new function
  • — to avoid memory leaks, the thread cannot hold pointers to OnTicker
  • — but the thread and OnTicker can both point to shared data onTick

func NewOnTicker added in v0.4.58

func NewOnTicker(period time.Duration, loc ...*time.Location) (onTicker *OnTicker)

NewOnTicker returns a ticker that ticks on period-multiples since zero time.

  • loc is optional time zone, default time.Local, other time zone is time.UTC
  • — time zone matters for periods longer than 1 hour or time-zone offiset minutes
  • period must be greater than zero or panic
  • OnTicker is a time.Ticker enhanced with on-period multiples

func (*OnTicker) Stop added in v0.4.58

func (o *OnTicker) Stop()

type Period added in v0.4.48

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

Period provides real-time based fixed-length interval perioding ordered using a uint64 zero-based index.

  • Period provides first period index and fractional usage of the first period

func NewPeriod added in v0.4.48

func NewPeriod(interval time.Duration) (period *Period)

NewPeriod returns a new numbered-interval sequence.

func (*Period) Available added in v0.4.48

func (p *Period) Available(now PeriodIndex, cap int) (periods int)

Available returns the correct number of slice entries to incldue now

  • after the inital few periods, returns cap
  • possible values 1… but no greater than cap
  • now cannot be less than period0

func (*Period) Index added in v0.4.48

func (p *Period) Index(t ...time.Time) (index PeriodIndex)

Index returns the index number for the current period or the period at time t

  • index is a number p.period0 or larger

func (*Period) Since added in v0.4.48

func (p *Period) Since(now, before PeriodIndex) (periods int)

Since returns the number of periods difference that now is greater than before

  • periods is >= 0
  • now and before must be at least p.period0
  • before cannot be greater than now

func (*Period) Sub added in v0.4.48

func (p *Period) Sub(now PeriodIndex, n int) (periodIndex PeriodIndex)

Sub returns a past period index by n intervals

  • periodIndex will not be less than p.period0
  • now cannot be less than p.period0

type PeriodIndex added in v0.4.48

type PeriodIndex uint64

type ThreadSafeTimer added in v0.4.121

type ThreadSafeTimer struct {

	// the timer initially stopped
	*time.Timer
	// contains filtered or unexported fields
}

ThreadSafeTimer is a timer that can be Reset by multiple threads. Improvements:

  • Stop and Reset are thread-safe
  • Reset includes Stop in a fail-safe sequence and can be invoked at any time by any thread
  • NewThreadSafeTimer has a defaultDuration of 1 second if argument is missing, zero or negative
  • Reset also uses defaultDuration if argument is zero or negative
  • fields and method signatures are identical to time.Timer
  • ThreadSafeTimer may be copied or stored in slices or maps
  • cost: 1 sync.Mutex, 1 int64, 2 pointers, 2 allocations
  • time.Timer public methods and fields: C Reset Stop
  • time.Timer Reset must be in an uninterrupted Stop-drain-Reset sequence or memory leaks result

func NewThreadSafeTimer added in v0.4.121

func NewThreadSafeTimer(defaultDuration ...time.Duration) (timer *ThreadSafeTimer)

NewThreadSafeTimer returns a running timer with thread-safe Reset

  • default defaultDuration is 1 second for defaultDuration missing, zero or negative
  • defaultDuration is the default for Reset when Reset argument is zero or negative
  • Reset can be invoked at any time without any precautions.
  • time.Timer.Reset has many conditions to avoid memory leaks
  • Stop and Reset methods are thread-safe
  • a timer must either expire or have Stop invoked to release resources
  • if timer was created in same thread or obtained via synchronize before, read of field C is thread-safe

func (*ThreadSafeTimer) Reset added in v0.4.121

func (t *ThreadSafeTimer) Reset(duration time.Duration)

Reset is thread-safe timer reset

  • has default duration for duration == 0
  • works with concurrent channel read
  • works with concurrent timer.Stop
  • thread-safety is obtained by making the Stop-drain-Reset sequence atomic
  • unsynchronized Reset will cause memory leaks

func (*ThreadSafeTimer) Stop added in v0.4.159

func (t *ThreadSafeTimer) Stop() (wasRunning bool)

Stop prevents the Timer from firing

Jump to

Keyboard shortcuts

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