MCGCDTimer.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // MCGCDTimer.swift
  3. // GCD Timer
  4. //
  5. // Created by Enhart on 2017/6/15.
  6. // Copyright © 2017年 Enhart. All rights reserved.
  7. //
  8. import UIKit
  9. typealias ActionBlock = () -> ()
  10. class MCGCDTimer {
  11. /// 单例
  12. static let shared = MCGCDTimer()
  13. private init(){}
  14. lazy var timerContainer = [String: DispatchSourceTimer]()
  15. /// GCD定时器
  16. ///
  17. /// - Parameters:
  18. /// - name: 定时器名字
  19. /// - timeInterval: 时间间隔
  20. /// - queue: 队列
  21. /// - repeats: 是否重复
  22. /// - action: 执行任务的闭包
  23. func scheduledDispatchTimer(WithTimerName name: String, timeInterval: Double, queue: DispatchQueue, repeats: Bool, action: @escaping ActionBlock) {
  24. if isExistTimer(WithTimerName: name) {
  25. self.cancleTimer(WithTimerName: name)
  26. }
  27. var timer = timerContainer[name]
  28. if timer == nil {
  29. timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
  30. timer?.resume()
  31. timerContainer[name] = timer
  32. }
  33. //精度0.1秒
  34. timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100))
  35. timer?.setEventHandler(handler: { [weak self] in
  36. action()
  37. if repeats == false {
  38. self?.cancleTimer(WithTimerName: name)
  39. }
  40. })
  41. }
  42. /// 取消定时器
  43. ///
  44. /// - Parameter name: 定时器名字
  45. func cancleTimer(WithTimerName name: String) {
  46. let timer = timerContainer[name]
  47. if timer == nil {
  48. return
  49. }
  50. timerContainer.removeValue(forKey: name)
  51. timer?.cancel()
  52. }
  53. /// 检查定时器是否已存在
  54. ///
  55. /// - Parameter name: 定时器名字
  56. /// - Returns: 是否已经存在定时器
  57. func isExistTimer(WithTimerName name: String?) -> Bool {
  58. if timerContainer[name!] != nil {
  59. return true
  60. }
  61. return false
  62. }
  63. }
  64. extension MCGCDTimer {
  65. /// 取消所有定时器
  66. func cancleAll() {
  67. let values = timerContainer.values
  68. values.forEach {
  69. $0.cancel()
  70. }
  71. timerContainer.removeAll()
  72. }
  73. }