README 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. [![GoDoc](http://godoc.org/github.com/ChimeraCoder/tokenbucket?status.png)](http://godoc.org/github.com/ChimeraCoder/tokenbucket)
  2. tokenbucket
  3. ====================
  4. This package provides an implementation of [Token bucket](https://en.wikipedia.org/wiki/Token_bucket) scheduling in Go. It is useful for implementing rate-limiting, traffic shaping, or other sorts of scheduling that depend on bandwidth constraints.
  5. Example
  6. ------------
  7. To create a new bucket, specify a capacity (how many tokens can be stored "in the bank"), and a rate (how often a new token is added).
  8. ````go
  9. // Create a new bucket
  10. // Allow a new action every 5 seconds, with a maximum of 3 "in the bank"
  11. bucket := tokenbucket.NewBucket(3, 5 * time.Second)
  12. ````
  13. This bucket should be shared between any functions that share the same constraints. (These functions may or may not run in separate goroutines).
  14. Anytime a regulated action is performed, spend a token.
  15. ````go
  16. // To perform a regulated action, we must spend a token
  17. // RegulatedAction will not be performed until the bucket contains enough tokens
  18. <-bucket.SpendToken(1)
  19. RegulatedAction()
  20. ````
  21. `SpendToken` returns immediately. Reading from the channel that it returns will block until the action has "permission" to continue (ie, until there are enough tokens in the bucket).
  22. (The channel that `SpendToken` returns is of type `error`. For now, the value will always be `nil`, so it can be ignored.)
  23. ####License
  24. `tokenbucket` is free software provided under version 3 of the LGPL license.
  25. Software that uses `tokenbucket` may be released under *any* license, as long as the source code for `tokenbucket` (including any modifications) are made available under the LGPLv3 license.
  26. You do not need to release the rest of the software under the LGPL, or any free/open-source license, for that matter (though we would encourage you to do so!).