ttl

package module
v0.0.0-...-d469d59 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2024 License: MIT Imports: 4 Imported by: 0

README

TTL

Generic concurency safe Time-To-Live list.

func ExampleTTL() {

	list := ttl.New[int](
		func(key int) {
			fmt.Printf("timed out: %v\n", key)
		},
	)
	list.Put(42, 1*time.Millisecond)

	<-list.Wait() // optionally wait for everything to time out.
	list.Stop()   // stops the internal worker.

	// Output:
	// timed out: 42
}

Uses channels for internals sync, operations are not time compensated. Timeout events are always a few microseconds late.

It stores keys in a slice sorted by key timeout in ascending order and continually resets a ticker that runs in a worker routine to a timeout of the next key in queue.

Has room for optimizations. Adding items whose timeout is always greater than the last in the list is fast but is slow if timeouts being added continually decrease, i.e. are put to the front of the key list.

goos: linux
goarch: amd64
pkg: github.com/vedranvuk/ttl
cpu: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
BenchmarkPutAscending
BenchmarkPutAscending-8           732739              1643 ns/op
BenchmarkPutDescending
BenchmarkPutDescending-8           40346            182233 ns/op
BenchmarkPutRandom
BenchmarkPutRandom-8               63727            146609 ns/op
PASS
ok      github.com/vedranvuk/ttl        20.472s

License

MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when delete does not find the item to be deleted.

View Source
var ErrNotRunning = errors.New("ttl is not running")

ErrNotRunning is returned when a timeout is being added or deleted to/from a ttl that has been stopped.

Functions

This section is empty.

Types

type TTL

type TTL[K comparable] struct {
	// contains filtered or unexported fields
}

TTL is a Time-To-Live list of comparrable keys that exist only for the duration specified. When a key expires TTL fires the callback specified in New.

TTL worker should be stopped manually after use with TTL.Stop.

It works by maintaining an ascending sorted queue of key timeout times that get on the next tick that is upated each time a timeout, update, put or delete occur updates a ticker that ticks at the next timeout time in the queue and fires timeout callback. Precision is "okay", error is always a delay.

Example
package main

import (
	"fmt"
	"time"

	"github.com/vedranvuk/ttl"
)

func main() {

	list := ttl.New[int](
		func(key int) {
			fmt.Printf("timed out: %v\n", key)
		},
	)
	list.Put(42, 1*time.Millisecond)

	<-list.Wait()
	list.Stop()

}
Output:
timed out: 42

func New

func New[K comparable](cb func(key K)) *TTL[K]

Returns a new TTL which calls the optional cb each time a key expires.

func (*TTL[K]) Delete

func (self *TTL[K]) Delete(key K) (err error)

Delete removes a key from the list. Returns ErrNotRunning if ttl is stopped.

func (*TTL[K]) Len

func (self *TTL[K]) Len() (l int)

Len returns the number of events in the list left to fire.

func (*TTL[K]) Put

func (self *TTL[K]) Put(key K, duration time.Duration) error

Put adds the key to ttl which will last for duration. If key is already present its timeout is reset to duration. Returns ErrNotRunning if ttl is stopped.

func (*TTL[K]) Stop

func (self *TTL[K]) Stop() error

Stop stops the worker. This method should be called on shutdown. Returns ErrNotRunning if ttl is already stopped.

func (*TTL[K]) Wait

func (self *TTL[K]) Wait() chan time.Time

Wait returns a channel that returns the current time when the TLL queue is empty and all events have fired.

Jump to

Keyboard shortcuts

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