Skip to content

Instantly share code, notes, and snippets.

@Abizern
Last active December 8, 2016 16:32
Show Gist options
  • Save Abizern/cf26af397ebe66284002 to your computer and use it in GitHub Desktop.
Save Abizern/cf26af397ebe66284002 to your computer and use it in GitHub Desktop.
A function that creates and starts a timer dispatch source.
//
// 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
}
@bibscy
Copy link

bibscy commented Dec 8, 2016

How do you stop the timer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment