Last active
December 8, 2016 16:32
-
-
Save Abizern/cf26af397ebe66284002 to your computer and use it in GitHub Desktop.
A function that creates and starts a timer dispatch source.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// RepeatingTimer.swift | |
// | |
import Foundation | |
enum TimerError: ErrorType { | |
/// The timer could not be created. | |
case CouldNotCreate | |
} | |
/** | |
Create and start a timer dispatch source. | |
This is best used for short running timers. Be sure to call `dispatch_source_cancel()` on the timer to invalidate it. | |
- Parameters: | |
- interval: The interval for the timer. | |
- leeway: The amount of time that the system can defer the timer. | |
- start: The start time of the timer. Defaults to DISPATCH_TIME_NOW | |
- queue: The dispatch queue to which the action closure is submitted. Defaults to the main queue. | |
- action: The closure to submit to the queue. Has the signature of () -> Void | |
- Returns: A dispatch source timer that has already been started. | |
- Throws: A `TimerError.CouldNotCreate` error if the timer could not be created. | |
*/ | |
@warn_unused_result | |
func repeatingTimerWithInterval( | |
interval: NSTimeInterval, | |
leeway: NSTimeInterval, | |
start: dispatch_time_t = DISPATCH_TIME_NOW, | |
queue: dispatch_queue_t = dispatch_get_main_queue(), | |
action: dispatch_block_t) | |
throws -> dispatch_source_t { | |
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) | |
guard timer != nil else { throw TimerError.CouldNotCreate } | |
func nanoseconds(seconds: NSTimeInterval) -> UInt64 { | |
enum Static { static let Multiplier = Double(NSEC_PER_SEC) } | |
return UInt64(seconds * Static.Multiplier) | |
} | |
dispatch_source_set_event_handler(timer, action) | |
dispatch_source_set_timer(timer, start, nanoseconds(interval), nanoseconds(leeway)) | |
dispatch_resume(timer) | |
return timer | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you stop the timer?