f2cf74c7
yangbin
1.0.20(4)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
//
// GCDTimer.swift
// zc
//
// Created by wyp on 2020/6/2.
// Copyright © 2020 wyp. All rights reserved.
//
import UIKit
typealias ActionBlock = () -> ()
class GCDTimer: NSObject {
static let shared = GCDTimer()
lazy var timerContainer = [String: DispatchSourceTimer]()
/// GCD定时器
///
/// - Parameters:
/// - name: 定时器名字
/// - timeInterval: 时间间隔
/// - queue: 队列
/// - repeats: 是否重复
/// - action: 执行任务的闭包
func scheduledDispatchTimer(WithTimerName name: String?, timeInterval: Double, queue: DispatchQueue, repeats: Bool, action: @escaping ActionBlock) {
if name == nil {
return
}
var timer = timerContainer[name!]
if timer == nil {
timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
timer?.resume()
timerContainer[name!] = timer
}
//精度0.1秒
timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100))
timer?.setEventHandler(handler: { [weak self] in
action()
if repeats == false {
self?.cancleTimer(WithTimerName: name)
}
})
}
func scheduledDispatchTimerNotNow(WithTimerName name: String?, timeInterval: Double, queue: DispatchQueue, repeats: Bool, action: @escaping ActionBlock) {
if name == nil {
return
}
var timer = timerContainer[name!]
if timer == nil {
timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
timer?.resume()
timerContainer[name!] = timer
}
//精度0.1秒
timer?.schedule(deadline: .now()+timeInterval, repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100))
timer?.setEventHandler(handler: { [weak self] in
action()
if repeats == false {
self?.cancleTimer(WithTimerName: name)
}
})
}
/// 取消定时器
///
/// - Parameter name: 定时器名字
func cancleTimer(WithTimerName name: String?) {
let timer = timerContainer[name!]
if timer == nil {
return
}
timerContainer.removeValue(forKey: name!)
timer?.cancel()
}
/// 检查定时器是否已存在
///
/// - Parameter name: 定时器名字
/// - Returns: 是否已经存在定时器
func isExistTimer(WithTimerName name: String?) -> Bool {
if timerContainer[name!] != nil {
return true
}
return false
}
}
|