Skip to content

Instantly share code, notes, and snippets.

@mrkev
Created August 5, 2018 05:48
Show Gist options
  • Save mrkev/ef489d4b71b8311a0a5fe4293bc98aa9 to your computer and use it in GitHub Desktop.
Save mrkev/ef489d4b71b8311a0a5fe4293bc98aa9 to your computer and use it in GitHub Desktop.
Some timer utilities
import Foundation
// I took this from: https://gist.github.com/peatiscoding/4f8699d8acd635746037b844f0730336
/**
setTimeout()
Shorthand method for create a delayed block to be execute on started Thread.
This method returns ``Timer`` instance, so that user may execute the block
within immediately or keep the reference for further cancelation by calling
``Timer.invalidate()``
Example:
let timer = setTimeout(0.3) {
// do something
}
timer.invalidate() // cancel it.
*/
func setTimeout(_ delay:TimeInterval, block:@escaping ()->Void) -> Timer {
return Timer.scheduledTimer(
timeInterval: delay,
target: BlockOperation(block: block),
selector: #selector(Operation.main),
userInfo: nil, repeats: false
)
}
// I wrote this
/**
* This timer automatically syncronizes to the nearest minute
* to save wakes/cpu cyles. Efficiency yo. Used to update the minute label.
*/
func setSynchInterval(block: @escaping () -> Void, onSet: @escaping (Timer) -> Void) {
let minsPast = Int(Date().timeIntervalSince1970) / 60;
let nextTick = Date(timeIntervalSince1970: TimeInterval(((minsPast * 60) + 60)))
let nextMin = nextTick.timeIntervalSinceNow
let _ = setTimeout(nextMin) {
block()
let interval = setInterval(60, block: block)
onSet(interval)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment