throttle

package module
v0.0.0-...-3af265e Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2023 License: MIT Imports: 3 Imported by: 1

README

throttle

Provides a simple interface for throttling function calls.

Installation

$ go get -u github.com/codingconcepts/throttle

Usage

package main

import (
	"fmt"
	"sync/atomic"
	"time"

	"github.com/codingconcepts/throttle"
)

func main() {
	// Create a new throttle of 10 ops/s.
	r := throttle.New(10, time.Second)

	var sum int64
	f := func() {
		atomic.AddInt64(&sum, 1)
	}

	// Run 20 times (takes 2s because we're running 10 ops/s).
	r.Do(context.Background(), 20, f)
	fmt.Printf("sum: %d\n", sum)
	// Outputs: 20

	// Run for 3 seconds.
	r.DoFor(context.Background(), time.Second*3, f)
	fmt.Printf("sum: %d\n", sum)
	// Outputs: 50
}

Documentation

Overview

Example
r := New(10, time.Second)

var sum int64
r.Do(context.Background(), 10, func() error {
	atomic.AddInt64(&sum, 1)
	return nil
})
log.Println("sum", sum)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner holds the methods of the interface.

func New

func New(rate int64, res time.Duration) *Runner

New returns a pointer to an instance of runner, which is used to perform all operations at the given rate in requests/s.

Rate and Res can be used in conjection to give you a run frequency. For example rate = 10, res = time.Second will run something 10 times every second.

func (*Runner) Do

func (r *Runner) Do(ctx context.Context, total int, f func() error) error

Do executes a function a given number of times. For example, if your throttler is configured to run 10 operations per second and you pass 50 for total, this will execute the function 50 times and take 5 seconds.

func (*Runner) DoFor

func (r *Runner) DoFor(ctx context.Context, d time.Duration, f func() error) error

DoFor executes a function for a given amount of time. For example, if your throttler is configured to run 10 operations per second and you pass 3 seconds for d, this will execute the function 30 times.

Jump to

Keyboard shortcuts

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