Documentation ¶
Overview ¶
Example ¶
package main import ( "fmt" "time" bucket "github.com/DavidCai1993/token-bucket" ) func main() { tb := bucket.New(time.Second, 1000) tb.Take(10) ok := tb.TakeMaxDuration(1000, 20*time.Second) fmt.Println(ok) // -> true tb.WaitMaxDuration(1000, 10*time.Second) fmt.Println(ok) // -> false tb.Wait(1000) }
Output:
Index ¶
- type TokenBucket
- func (tb *TokenBucket) Availible() int64
- func (tb *TokenBucket) Capability() int64
- func (tb *TokenBucket) Destory()
- func (tb *TokenBucket) Take(count int64)
- func (tb *TokenBucket) TakeMaxDuration(count int64, max time.Duration) bool
- func (tb *TokenBucket) TryTake(count int64) bool
- func (tb *TokenBucket) Wait(count int64)
- func (tb *TokenBucket) WaitMaxDuration(count int64, max time.Duration) bool
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type TokenBucket ¶
type TokenBucket struct {
// contains filtered or unexported fields
}
TokenBucket represents a token bucket (https://en.wikipedia.org/wiki/Token_bucket) which based on multi goroutines, and is safe to use under concurrency environments.
func New ¶
func New(interval time.Duration, cap int64) *TokenBucket
New returns a new token bucket with specified fill interval and capability. The bucket is initially full.
func (*TokenBucket) Availible ¶
func (tb *TokenBucket) Availible() int64
Availible returns how many tokens are availible in the bucket.
func (*TokenBucket) Capability ¶
func (tb *TokenBucket) Capability() int64
Capability returns the capability of this token bucket.
func (*TokenBucket) Destory ¶
func (tb *TokenBucket) Destory()
Destory destorys the token bucket and stop the inner channels.
func (*TokenBucket) Take ¶
func (tb *TokenBucket) Take(count int64)
Take tasks specified count tokens from the bucket, if there are not enough tokens in the bucket, it will keep waiting until count tokens are availible and then take them.
func (*TokenBucket) TakeMaxDuration ¶
func (tb *TokenBucket) TakeMaxDuration(count int64, max time.Duration) bool
TakeMaxDuration tasks specified count tokens from the bucket, if there are not enough tokens in the bucket, it will keep waiting until count tokens are availible and then take them or just return false when reach the given max duration.
func (*TokenBucket) TryTake ¶
func (tb *TokenBucket) TryTake(count int64) bool
TryTake trys to task specified count tokens from the bucket. if there are not enough tokens in the bucket, it will return false.
func (*TokenBucket) Wait ¶
func (tb *TokenBucket) Wait(count int64)
Wait will keep waiting until count tokens are availible in the bucket.
func (*TokenBucket) WaitMaxDuration ¶
func (tb *TokenBucket) WaitMaxDuration(count int64, max time.Duration) bool
WaitMaxDuration will keep waiting until count tokens are availible in the bucket or just return false when reach the given max duration.