wait_time.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /*
  15. Copyright 2015 CoreOS, Inc.
  16. Licensed under the Apache License, Version 2.0 (the "License");
  17. you may not use this file except in compliance with the License.
  18. You may obtain a copy of the License at
  19. http://www.apache.org/licenses/LICENSE-2.0
  20. Unless required by applicable law or agreed to in writing, software
  21. distributed under the License is distributed on an "AS IS" BASIS,
  22. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. See the License for the specific language governing permissions and
  24. limitations under the License.
  25. */
  26. package wait
  27. import (
  28. "sync"
  29. "time"
  30. )
  31. type WaitTime interface {
  32. // Wait returns a chan that waits on the given deadline.
  33. // The chan will be triggered when Trigger is called with a
  34. // deadline that is later than the one it is waiting for.
  35. // The given deadline MUST be unique. The deadline should be
  36. // retrived by calling time.Now() in most cases.
  37. Wait(deadline time.Time) <-chan struct{}
  38. // Trigger triggers all the waiting chans with an earlier deadline.
  39. Trigger(deadline time.Time)
  40. }
  41. type timeList struct {
  42. l sync.Mutex
  43. m map[int64]chan struct{}
  44. }
  45. func NewTimeList() *timeList {
  46. return &timeList{m: make(map[int64]chan struct{})}
  47. }
  48. func (tl *timeList) Wait(deadline time.Time) <-chan struct{} {
  49. tl.l.Lock()
  50. defer tl.l.Unlock()
  51. ch := make(chan struct{}, 1)
  52. // The given deadline SHOULD be unique.
  53. tl.m[deadline.UnixNano()] = ch
  54. return ch
  55. }
  56. func (tl *timeList) Trigger(deadline time.Time) {
  57. tl.l.Lock()
  58. defer tl.l.Unlock()
  59. for t, ch := range tl.m {
  60. if t < deadline.UnixNano() {
  61. delete(tl.m, t)
  62. close(ch)
  63. }
  64. }
  65. }