http://www.jianshu.com/p/583ca675065a
import UIKit
class XTimer: NSObject {
var ti:TimeInterval!
var atarget:AnyObject!
var aSelector:Selector!
var userInfo:Any?
private var isValid = true
private var yesOrNo = true
override init() {
super.init()
}
class func scheduledTimer(timeInterval ti:TimeInterval,target aTarget:Any,selector aSelector:Selector,userInfo:Any?,repeats yesOrNo:Bool)->XTimer{
let timer = XTimer()
timer.ti = ti
timer.atarget = aTarget as AnyObject!
timer.aSelector = aSelector
timer.userInfo = userInfo
if yesOrNo{
timer.repeatSelector()
}else{
let popTime = DispatchTime.now() + ti
DispatchQueue.main.asyncAfter(deadline: popTime) {
(aTarget as AnyObject!).performSelector(onMainThread: aSelector, with: userInfo, waitUntilDone: false)
}
}
return timer
}
func repeatSelector(){
let popTime = DispatchTime.now() + ti
DispatchQueue.main.asyncAfter(deadline: popTime) {
if self.yesOrNo{
(self.atarget as AnyObject!).performSelector(onMainThread: self.aSelector, with: self.userInfo, waitUntilDone: false)
}
if self.isValid{
self.repeatSelector()
}
}
}
func reStart(){
yesOrNo = true
}
func stop(){
yesOrNo = false
}
func invalidate(){
isValid = false
}
}