let timer:ATimer = Timer.makeFirendlyTimer(for type: .one)
let aClosure:()->Void = {...}
timer.job = aClosure
timer.start()
timer.stop()
protocol ATimer { | |
func start() | |
func stop() | |
var isRuning:Bool{get} | |
var timeInterval:TimeInterval{get set} | |
typealias Job = ()->Void | |
} | |
class AReapeatTimer:ATimer{ | |
var isRuning: Bool {return timer != nil} | |
init(job: @escaping Job) { | |
self.job = job | |
} | |
init(){} | |
var timeInterval:TimeInterval = 0.1 | |
var job:Job! | |
func start(){ | |
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerJob), userInfo: nil, repeats: true) | |
} | |
func stop() { | |
timer?.invalidate() | |
timer = nil | |
} | |
@objc | |
fileprivate func timerJob() { job() } | |
fileprivate var timer:Timer? | |
} | |
class AOneTimer: AReapeatTimer { | |
override func start() { | |
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerJob), userInfo: nil, repeats: false) | |
} | |
} |
import Foundation.NSTimer | |
extension Timer{ | |
enum TimerType{ | |
case repeated, one | |
} | |
static func makeFirendlyTimer(for type:TimerType) -> ATimer{ | |
var aTimer:ATimer | |
switch type { | |
case .repeated: | |
aTimer = AReapeatTimer() | |
case .one: | |
aTimer = AOneTimer() | |
} | |
return aTimer | |
} | |
} |