timer.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package mhayaTimeWheel
  2. import (
  3. "container/list"
  4. "sync/atomic"
  5. "unsafe"
  6. )
  7. // Timer represents a single event. When the Timer expires, the given
  8. // task will be executed.
  9. type Timer struct {
  10. id uint64
  11. expiration int64 // in milliseconds
  12. task func()
  13. // The bucket that holds the list to which this timer's element belongs.
  14. //
  15. // NOTE: This field may be updated and read concurrently,
  16. // through Timer.Stop() and Bucket.Flush().
  17. b unsafe.Pointer // type: *bucket
  18. element *list.Element // The timer's element.
  19. isAsync bool // async execute task
  20. }
  21. func (t *Timer) ID() uint64 {
  22. return t.id
  23. }
  24. func (t *Timer) getBucket() *bucket {
  25. return (*bucket)(atomic.LoadPointer(&t.b))
  26. }
  27. func (t *Timer) setBucket(b *bucket) {
  28. atomic.StorePointer(&t.b, unsafe.Pointer(b))
  29. }
  30. // Stop prevents the Timer from firing. It returns true if the call
  31. // stops the timer, false if the timer has already expired or been stopped.
  32. //
  33. // If the timer t has already expired and the t.task has been started in its own
  34. // goroutine; Stop does not wait for t.task to complete before returning. If the caller
  35. // needs to know whether t.task is completed, it must coordinate with t.task explicitly.
  36. func (t *Timer) Stop() bool {
  37. stopped := false
  38. for b := t.getBucket(); b != nil; b = t.getBucket() {
  39. // If b.Remove is called just after the timing wheel's goroutine has:
  40. // 1. removed t from b (through b.Flush -> b.remove)
  41. // 2. moved t from b to another bucket ab (through b.Flush -> b.remove and ab.Add)
  42. // this may fail to remove t due to the change of t's bucket.
  43. stopped = b.Remove(t)
  44. // Thus, here we re-get t's possibly new bucket (nil for case 1, or ab (non-nil) for case 2),
  45. // and retry until the bucket becomes nil, which indicates that t has finally been removed.
  46. }
  47. return stopped
  48. }