github.com/haraldrudell/parl@v0.4.176/invocation.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package parl 7 8 import ( 9 "sync/atomic" 10 "time" 11 ) 12 13 // a timed invocation created by [InvokeTimer.Invocation] 14 // - holds invocation instance-data for [InvocationTimer.invocationEnd] 15 type Invocation[T any] struct { 16 Prev, Next atomic.Pointer[Invocation[T]] 17 ThreadID ThreadID 18 Value T 19 t0 time.Time 20 invocationEnd func(invocation *Invocation[T], duration time.Duration) 21 } 22 23 // NewInvocation adds a new invocation to [InvokeTimer] 24 // - holds invocation instance-data for [InvocationTimer.invocationEnd] 25 func NewInvocation[T any](invocationEnd func(invocation *Invocation[T], duration time.Duration), value T) (invocation *Invocation[T]) { 26 return &Invocation[T]{ 27 ThreadID: goID(), 28 Value: value, 29 t0: time.Now(), 30 invocationEnd: invocationEnd, 31 } 32 } 33 34 // DeferFunc ends an invocation 35 // - provides invocation instance-data for [InvocationTimer.invocationEnd] 36 func (i *Invocation[T]) DeferFunc() { i.invocationEnd(i, i.Age()) } 37 38 // Age returns the current age of this invocation 39 func (i *Invocation[T]) Age() (age time.Duration) { 40 var t1 = time.Now() 41 age = t1.Sub(i.t0) 42 return 43 }