safetimer.go 691 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // SafeTime add thread-safe for time.Timer
  7. type SafeTimer struct {
  8. *time.Timer
  9. mu sync.Mutex
  10. duration time.Duration
  11. }
  12. func NewSafeTimer(d time.Duration) *SafeTimer {
  13. return &SafeTimer{
  14. Timer: time.NewTimer(d),
  15. duration: d,
  16. }
  17. }
  18. // Reset is thread-safe now, accept one or none argument
  19. func (t *SafeTimer) Reset(ds ...time.Duration) bool {
  20. t.mu.Lock()
  21. defer t.mu.Unlock()
  22. if len(ds) > 0 {
  23. if len(ds) != 1 {
  24. panic("SafeTimer.Reset only accept at most one argument")
  25. }
  26. t.duration = ds[0]
  27. }
  28. return t.Timer.Reset(t.duration)
  29. }
  30. func (t *SafeTimer) Stop() bool {
  31. t.mu.Lock()
  32. defer t.mu.Unlock()
  33. return t.Timer.Stop()
  34. }