work_queue.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package queue
  14. import (
  15. "sync"
  16. "time"
  17. "k8s.io/apimachinery/pkg/types"
  18. "k8s.io/apimachinery/pkg/util/clock"
  19. )
  20. // WorkQueue allows queuing items with a timestamp. An item is
  21. // considered ready to process if the timestamp has expired.
  22. type WorkQueue interface {
  23. // GetWork dequeues and returns all ready items.
  24. GetWork() []types.UID
  25. // Enqueue inserts a new item or overwrites an existing item.
  26. Enqueue(item types.UID, delay time.Duration)
  27. }
  28. type basicWorkQueue struct {
  29. clock clock.Clock
  30. lock sync.Mutex
  31. queue map[types.UID]time.Time
  32. }
  33. var _ WorkQueue = &basicWorkQueue{}
  34. // NewBasicWorkQueue returns a new basic WorkQueue with the provided clock
  35. func NewBasicWorkQueue(clock clock.Clock) WorkQueue {
  36. queue := make(map[types.UID]time.Time)
  37. return &basicWorkQueue{queue: queue, clock: clock}
  38. }
  39. func (q *basicWorkQueue) GetWork() []types.UID {
  40. q.lock.Lock()
  41. defer q.lock.Unlock()
  42. now := q.clock.Now()
  43. var items []types.UID
  44. for k, v := range q.queue {
  45. if v.Before(now) {
  46. items = append(items, k)
  47. delete(q.queue, k)
  48. }
  49. }
  50. return items
  51. }
  52. func (q *basicWorkQueue) Enqueue(item types.UID, delay time.Duration) {
  53. q.lock.Lock()
  54. defer q.lock.Unlock()
  55. q.queue[item] = q.clock.Now().Add(delay)
  56. }