throttle

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2021 License: MIT Imports: 2 Imported by: 2

README

Throttle

test workflow Go Report Card Coverage Status

Throttle is an object that will perform exactly one action per duration. Do call the function f if a specified duration has passed since the last function f was called for this instance of Throttle.

Group 38 (1)

Examples

single thread
package main

import (
	"fmt"
	"time"

	"github.com/yudppp/throttle"
)

func main() {
	throttler := throttle.New(time.Second)
	throttler.Do(func() {
		fmt.Println("first call")
	})
	throttler.Do(func() {
		// this function called never.
		fmt.Println("second call")
	})
	time.Sleep(time.Second)
	throttler.Do(func() {
		fmt.Println("third call")
	})
	time.Sleep(time.Second)
}
$ go run -race main.go
first call
third call
multiple threads
package main

import (
	"fmt"
	"time"

	"github.com/yudppp/throttle"
)

func main() {
	throttler := throttle.New(time.Second)
	var wg sync.WaitGroup
	for i := 0; i < 64; i++ {
		wg.Add(1)
		go func(i int) {
			throttler.Do(func() {
				fmt.Println("called")
			})
			wg.Done()
		}(i)
	}
	wg.Wait()
}
$ go run -race main.go
called

License

The MIT License (MIT)

Documentation

Overview

Package throttle is function throttling package

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Throttler

type Throttler interface {
	Do(f func())
}

Throttler is an interface that will perform exactly one action per duration.(should use New constructor only) Do call the function f if a specified duration has passed since the last function f was called for this instance of Throttle. In other words, given

var throttle = Throttle.New(time.Minute)

if throttle.Do(f) is called multiple times within a minute, only the first call will invoke f, even if f has a different value in each invocation. Waiting for a minute or a new instance of Throttle is required for each function to execute.

func New

func New(duration time.Duration) Throttler

New create a new Throttler. The duration variable sets the duration to restrict Do function argument function f.

Jump to

Keyboard shortcuts

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