PQWeakTimer.swift 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // PQWeakTimer.swift
  3. // PQSpeed
  4. //
  5. // Created by lieyunye on 2020/6/18.
  6. // Copyright © 2020 BytesFlow. All rights reserved.
  7. //
  8. import Foundation
  9. public class PQWeakTimer {
  10. public weak var timer: Timer?
  11. public weak var target: AnyObject?
  12. public let action: (Timer) -> Void
  13. public init(timeInterval: TimeInterval,
  14. target: AnyObject,
  15. repeats: Bool,
  16. action: @escaping (Timer) -> Void)
  17. {
  18. self.target = target
  19. self.action = action
  20. timer = Timer.scheduledTimer(timeInterval: timeInterval,
  21. target: self,
  22. selector: #selector(fire),
  23. userInfo: nil,
  24. repeats: repeats)
  25. }
  26. public class func scheduledTimer(timeInterval: TimeInterval,
  27. target: AnyObject,
  28. repeats: Bool,
  29. action: @escaping (Timer) -> Void) -> Timer
  30. {
  31. return PQWeakTimer(timeInterval: timeInterval,
  32. target: target,
  33. repeats: repeats,
  34. action: action).timer!
  35. }
  36. @objc public func fire(timer: Timer) {
  37. if target != nil {
  38. action(timer)
  39. } else {
  40. timer.invalidate()
  41. }
  42. }
  43. }