Timer.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import NIOCore
  17. struct Timer {
  18. /// The delay to wait before running the task.
  19. private let delay: TimeAmount
  20. /// The task to run, if scheduled.
  21. private var task: Kind?
  22. /// Whether the task to schedule is repeated.
  23. private let `repeat`: Bool
  24. private enum Kind {
  25. case once(Scheduled<Void>)
  26. case repeated(RepeatedTask)
  27. func cancel() {
  28. switch self {
  29. case .once(let task):
  30. task.cancel()
  31. case .repeated(let task):
  32. task.cancel()
  33. }
  34. }
  35. }
  36. init(delay: TimeAmount, repeat: Bool = false) {
  37. self.delay = delay
  38. self.task = nil
  39. self.repeat = `repeat`
  40. }
  41. /// Schedule a task on the given `EventLoop`.
  42. mutating func schedule(on eventLoop: EventLoop, work: @escaping () throws -> Void) {
  43. self.task?.cancel()
  44. if self.repeat {
  45. let task = eventLoop.scheduleRepeatedTask(initialDelay: self.delay, delay: self.delay) { _ in
  46. try work()
  47. }
  48. self.task = .repeated(task)
  49. } else {
  50. let task = eventLoop.scheduleTask(in: self.delay, work)
  51. self.task = .once(task)
  52. }
  53. }
  54. /// Cancels the task, if one was scheduled.
  55. mutating func cancel() {
  56. self.task?.cancel()
  57. self.task = nil
  58. }
  59. }