RepeatingTimer.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // RepeatingTimer.swift
  3. // JourneyGPSTracker
  4. //
  5. // Created by Thomas Chef on 2022-04-30.
  6. // Copyright © 2022 Thomas Chef. All rights reserved.
  7. //
  8. import Foundation
  9. class RepeatingTimer {
  10. let timeInterval: TimeInterval
  11. init(timeInterval: TimeInterval) {
  12. self.timeInterval = timeInterval
  13. }
  14. private lazy var timer: DispatchSourceTimer = {
  15. let t = DispatchSource.makeTimerSource()
  16. t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
  17. t.setEventHandler(handler: { [weak self] in
  18. self?.eventHandler?()
  19. })
  20. return t
  21. }()
  22. var eventHandler: (() -> Void)?
  23. private enum State {
  24. case suspended
  25. case resumed
  26. }
  27. private var state: State = .suspended
  28. func resume() {
  29. if state == .resumed {
  30. return
  31. }
  32. state = .resumed
  33. timer.resume()
  34. }
  35. func suspend() {
  36. if state == .suspended {
  37. return
  38. }
  39. state = .suspended
  40. timer.suspend()
  41. }
  42. }