Skip to content

Instantly share code, notes, and snippets.

@drosenstark
Last active May 9, 2018 05:33
Show Gist options
  • Save drosenstark/f86abf58a8c997d208392a1cce0bc903 to your computer and use it in GitHub Desktop.
Save drosenstark/f86abf58a8c997d208392a1cce0bc903 to your computer and use it in GitHub Desktop.
A drop-in Swift replacement for NSTimer: faster and lighter weight using GCD
// DRTimer.swift
// ConfusionUtilFramework
//
// Created by dan on 5/4/17.
// Copyright © 2017 Confusion Studios LLC. All rights reserved.
//
import UIKit
// a faster timer than NSTimer, drop in replacement for
// just one of the methods... it's not precise but it works...
@objc(DRTimer)
open class DRTimer : NSObject {
static var queue:DispatchQueue = DispatchQueue(label: "com.dr2050.DRTimer", attributes: .concurrent)
var timer: DispatchSourceTimer!
open var userInfo:Any?
// most code is from here: http://stackoverflow.com/a/39581096/8047
// NOTE: repeats is always true... if you don't want a repeating timer, use
// dispatch_after
open class func scheduledTimer(timeInterval ti: TimeInterval, target aTarget: Any, selector aSelector: Selector, userInfo:Any?=nil) -> DRTimer {
let retVal = DRTimer()
let timer = DispatchSource.makeTimerSource(queue: DRTimer.queue)
retVal.timer = timer
retVal.userInfo = userInfo
let microseconds = Int(ti * 1000000)
timer.scheduleRepeating(deadline: .now(), interval: .microseconds(microseconds))
timer.setEventHandler {
if let target = aTarget as? NSObject {
target.perform(aSelector, with: retVal)
}
}
timer.resume()
return retVal
}
open var isValid:Bool {
guard let timer = timer else { return false }
return !timer.isCancelled
}
open func invalidate() {
timer?.cancel()
userInfo = nil
timer = nil
}
deinit {
invalidate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment