throttle

package module
v0.0.0-...-8018c89 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2021 License: MIT Imports: 2 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-throttle

Golang function throttler.
Similar to debounce, but the first call will execute immediately.
Subsequent calls will always have a minimum duration between executions.

Examples

Simple usage:

throttler := throttle.New(time.Millisecond * 250)

for i := 0; i < 10; i++ {
    if i == 0 {
        throttler(func() { fmt.Println("hello")})
    } else {
        throttler(func() { fmt.Println("world")})	
    }
    time.Sleep(time.Millisecond * 10)
}

// Output:
// hello (immediately)
// world (after 250 ms)

Reloading a cache with a 5m minimum interval:

package cache

import (
    "sync"
    "time"
    
    "github.com/frostbyte73/go-throttle"
)

type DataSource interface {
    Reload() map[string]interface{}
}

type Cache struct {
    DataSource
    
    mu         sync.RWMutex
    data       map[string]interface{}
    throttle   func(func())
}

func NewCache(source DataSource) *Cache {
    c := &Cache{
        DataSource: source,
        throttle:   throttle.New(time.Minute * 5),
    }
    
    // load initial cache data
    c.throttle(c.reloadCache)
    
    return c
}

func (c *Cache) Get(key string) interface{} {
    c.mu.RLock()
    defer c.mu.RUnlock()
    
    value, ok := c.data[key]
    if !ok {
        // cache miss - queue a reload, max once every 5 minutes
        c.throttle(c.reloadCache)
    }
    return value
}

func (c *Cache) reloadCache() {
    c.mu.Lock()
    defer c.mu.Unlock()
    
    c.data = c.DataSource.Reload()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(after time.Duration) func(f func())

New returns a function throttler that takes a function as its argument. If ready, it will execute immediately, and it will always wait the specified duration between executions. The last function added will be the function executed.

Types

This section is empty.

Jump to

Keyboard shortcuts

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