heartbeat.go 974 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package heartbeat
  2. import (
  3. "sync/atomic"
  4. "time"
  5. )
  6. // Heartbeat is simple way to track heartbeats.
  7. type Heartbeat struct {
  8. timeout int64
  9. timer *time.Timer
  10. }
  11. // New creates new Heartbeat with specified duration. timeoutFunc will be called
  12. // if timeout for heartbeat is expired. Note that in case of timeout you need to
  13. // call Beat() to reactivate Heartbeat.
  14. func New(timeout time.Duration, timeoutFunc func()) *Heartbeat {
  15. hb := &Heartbeat{
  16. timeout: int64(timeout),
  17. timer: time.AfterFunc(timeout, timeoutFunc),
  18. }
  19. return hb
  20. }
  21. // Beat resets internal timer to zero. It also can be used to reactivate
  22. // Heartbeat after timeout.
  23. func (hb *Heartbeat) Beat() {
  24. hb.timer.Reset(time.Duration(atomic.LoadInt64(&hb.timeout)))
  25. }
  26. // Update updates internal timeout to d. It does not do Beat.
  27. func (hb *Heartbeat) Update(d time.Duration) {
  28. atomic.StoreInt64(&hb.timeout, int64(d))
  29. }
  30. // Stop stops Heartbeat timer.
  31. func (hb *Heartbeat) Stop() {
  32. hb.timer.Stop()
  33. }