You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.1 KiB
76 lines
2.1 KiB
// |
|
// GCDTimer.swift |
|
// FireBoltt |
|
// |
|
// Created by lemo on 2018/5/20. |
|
// Copyright © 2020年 ecell. All rights reserved. |
|
// |
|
|
|
import UIKit |
|
|
|
class GCDTimer: NSObject { |
|
/// 单例 |
|
static let shared = GCDTimer() |
|
/// 需要在oc中调用此单例 |
|
@objc open class func ocShareInstance() -> GCDTimer { |
|
return shared |
|
} |
|
lazy var timerContainer = [String: DispatchSourceTimer]() |
|
|
|
/// GCD定时器 |
|
/// |
|
/// - Parameters: |
|
/// - name: 定时器名字 |
|
/// - timeInterval: 时间间隔 |
|
/// - queue: 队列 |
|
/// - repeats: 是否重复 |
|
/// - immediately: 是否立即执行 |
|
/// - action: 执行任务的闭包 |
|
@objc |
|
func scheduledDispatchTimer(WithTimerName name: String?, timeInterval: Double, queue: DispatchQueue, repeats: Bool, immediately: Bool, action: @escaping ActionClosure) { |
|
|
|
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: immediately ? .now() : .now() + timeInterval, repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100)) |
|
timer?.setEventHandler(handler: { [weak self] in |
|
action() |
|
if repeats == false { |
|
self?.cancleTimer(WithTimerName: name) |
|
} |
|
}) |
|
} |
|
|
|
/// 取消定时器 |
|
/// |
|
/// - Parameter name: 定时器名字 |
|
@objc |
|
func cancleTimer(WithTimerName name: String?) { |
|
let timer = timerContainer[name!] |
|
if timer == nil { |
|
return |
|
} |
|
timerContainer.removeValue(forKey: name!) |
|
timer?.cancel() |
|
} |
|
|
|
/// 检查定时器是否已存在 |
|
/// |
|
/// - Parameter name: 定时器名字 |
|
/// - Returns: 是否已经存在定时器 |
|
@objc |
|
func isExistTimer(WithTimerName name: String?) -> Bool { |
|
if timerContainer[name!] != nil { |
|
return true |
|
} |
|
return false |
|
} |
|
}
|
|
|