123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- //
- // RepeatingTimer.swift
- // JourneyGPSTracker
- //
- // Created by Thomas Chef on 2022-04-30.
- // Copyright © 2022 Thomas Chef. All rights reserved.
- //
- import Foundation
- class RepeatingTimer {
- let timeInterval: TimeInterval
- init(timeInterval: TimeInterval) {
- self.timeInterval = timeInterval
- }
- private lazy var timer: DispatchSourceTimer = {
- let t = DispatchSource.makeTimerSource()
- t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
- t.setEventHandler(handler: { [weak self] in
- self?.eventHandler?()
- })
- return t
- }()
- var eventHandler: (() -> Void)?
- private enum State {
- case suspended
- case resumed
- }
- private var state: State = .suspended
- func resume() {
- if state == .resumed {
- return
- }
- state = .resumed
- timer.resume()
- }
-
- func suspend() {
- if state == .suspended {
- return
- }
- state = .suspended
- timer.suspend()
- }
- }
|