rated

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2023 License: MPL-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package rated controls rate of a task with rate.Limiter.

A rated task focus on "How long I should wait before I can run again". You might want to take a look at package example to compare it with task.Task.Timed.

It is putted in seperated package so you won't link to unused external dependencies if you're not using it.

It's quite common to write following code:

err = Every(
	time.Minute,
	task.T(mytask).
		TimedFail(3*time.Second).
		RetryN(3).
		HandleErr(logError).
		IgnoreErr(),
).Loop().Run(ctx)

The above program will repeatedly execute mytask, with a maximum of one successful execution per minute. If the execution is not successful, it will be retried at an interval of once every three seconds for a total of three attempts. If all three retry attempts fail, the final error will be logged, treating it as a successful attempt, and continues to next run.

Example
t := func(_ context.Context) error { return nil }
timed := task.Task(t).Timed(time.Second)
rl := Every(time.Second, task.Task(t))
ctx := context.Background()

begin := time.Now()
timed.Run(ctx) // run t, wait a second
timed.Run(ctx) // run t, wait a second
timed.Run(ctx) // run t, wait a second
fmt.Printf("timed task: elapsed %d seconds\n", time.Since(begin)/time.Second)

begin = time.Now()
rl.Run(ctx) // run t
rl.Run(ctx) // wait a second, run t
rl.Run(ctx) // wait a second, run t
fmt.Printf("ratelimited task: elapsed %d seconds\n", time.Since(begin)/time.Second)
Output:

timed task: elapsed 3 seconds
ratelimited task: elapsed 2 seconds

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Every

func Every(dur time.Duration, f task.Task) task.Task

Every is a wrapper of New.

func New

func New(l *rate.Limiter, t task.Task) (ret task.Task)

New creates a task.Task that respects the rate limit.

Say you have an empty task r with rate limit to once per second:

r.Run() // executed immediatly
r.Run() // executed after a second

Types

This section is empty.

Jump to

Keyboard shortcuts

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