Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom completion handler queue #90

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions Sources/Clock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,25 +63,30 @@ public struct Clock {
/// - parameter pool: NTP pool that will be resolved into multiple NTP servers that will be used for
/// the synchronization.
/// - parameter samples: The number of samples to be acquired from each server (default 4).
/// - parameter queue: The queue on which the completion handler is dispatched. (default `.main`).
/// - parameter completion: A closure that will be called after _all_ the NTP calls are finished.
/// - parameter first: A closure that will be called after the first valid date is calculated.
public static func sync(from pool: String = "time.apple.com", samples: Int = 4,
public static func sync(from pool: String = "time.apple.com",
samples: Int = 4,
queue: DispatchQueue = .main,
first: ((Date, TimeInterval) -> Void)? = nil,
completion: ((Date?, TimeInterval?) -> Void)? = nil)
{
self.loadFromDefaults()

NTPClient().query(pool: pool, numberOfSamples: samples) { offset, done, total in
if let offset = offset {
self.stableTime = TimeFreeze(offset: offset)
queue.async {
if let offset = offset {
self.stableTime = TimeFreeze(offset: offset)

if done == 1, let now = self.now {
first?(now, offset)
if done == 1, let now = self.now {
first?(now, offset)
}
}
}

if done == total {
completion?(self.now, offset)
if done == total {
completion?(self.now, offset)
}
}
}
}
Expand Down
20 changes: 20 additions & 0 deletions Tests/KronosTests/ClockTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,24 @@ final class ClockTests: XCTestCase {

self.waitForExpectations(timeout: 20)
}

func testCustomQueue() {
let expectation = self.expectation(description: "Clock sync calls closure")
expectation.expectedFulfillmentCount = 2

let queue = DispatchQueue(label: "com.Lyft.Kronos.Test")

Clock.sync(
queue: queue,
first: { _, _ in
XCTAssertFalse(Thread.isMainThread)
expectation.fulfill()
},
completion: { _, _ in
XCTAssertFalse(Thread.isMainThread)
expectation.fulfill()
})

self.waitForExpectations(timeout: 20)
}
}