Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when delete does not find the item to be deleted.
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 ¶
Delete removes a key from the list. Returns ErrNotRunning if ttl is stopped.
func (*TTL[K]) Put ¶
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.