instance.go 723 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package canceler
  2. import (
  3. "context"
  4. "time"
  5. )
  6. type Instance struct {
  7. ctx context.Context
  8. cancelFunc context.CancelFunc
  9. timer *time.Timer
  10. timeout time.Duration
  11. }
  12. func New(ctx context.Context, cancelFunc context.CancelFunc, timeout time.Duration) *Instance {
  13. instance := &Instance{
  14. ctx,
  15. cancelFunc,
  16. time.NewTimer(timeout),
  17. timeout,
  18. }
  19. go instance.wait()
  20. return instance
  21. }
  22. func (i *Instance) Update() bool {
  23. if !i.timer.Stop() {
  24. return false
  25. }
  26. if !i.timer.Reset(i.timeout) {
  27. return false
  28. }
  29. return true
  30. }
  31. func (i *Instance) wait() {
  32. select {
  33. case <-i.timer.C:
  34. case <-i.ctx.Done():
  35. }
  36. i.Close()
  37. }
  38. func (i *Instance) Close() error {
  39. i.timer.Stop()
  40. i.cancelFunc()
  41. return nil
  42. }