##Creating a timer with Grand Central Dispatch
At the following is the implementation file of a sample class that shows, how to make a timer with the help of Grand Central Dispatch. The timer fires on a global queue, just change the queue to the main queue or any custom queue and the timer fires on this queue and not on the global queue anymore.
This was modified for swift 2.2 Also created an example of a background global queue variable. As well as a callback in the start timer so you can do some cool stuff everytime the timer is called.
/*
* GlobalBackgroundQueue
*
*/
var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.rawValue), 0)
}
/*
* var count = 10
* let gcdTimer = GCDTimer()
* gcdTimer.startTimer(){
* print("Count = \(count)")
* if count <= 0 {
* gcdTimer.cancelTimer()
* }
* count -= 1
* }
*
*/
class GCDBackgroundTimer {
var _timer: dispatch_source_t?
func createDispatchTimer(interval i: Double, queue: dispatch_queue_t, block:()->Void) -> dispatch_source_t?{
let iInt64 = Int64(i * Double(NSEC_PER_SEC))
let iUnt64 = UInt64(iInt64)
let ull: CUnsignedLongLong = 1
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, iInt64)
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer, dispatchTime, iUnt64, (ull * NSEC_PER_SEC)/10)
dispatch_source_set_event_handler(timer, block)
dispatch_resume(timer)
print("Timer \(timer)")
return timer
}
func startTimer(interval: Double = 1.0, eventHandler: ()->Void){
let queue = GlobalBackgroundQueue
let interval:Double = 1.000
_timer = createDispatchTimer(interval: interval, queue: queue){
// Do something here!
print("Running timer on main thread \(NSThread.isMainThread())")
eventHandler()
}
}
func cancelTimer(){
guard let timer = _timer else { return }
dispatch_source_cancel(timer)
_timer = nil
}
}