From 76c79b81bdb414a56cc55f8b838be83e1e2abf31 Mon Sep 17 00:00:00 2001 From: maxep Date: Thu, 23 Sep 2021 11:50:45 +0200 Subject: [PATCH] Add custom completion handler queue Signed-off-by: maxep --- Sources/Clock.swift | 21 +++++++++++++-------- Tests/KronosTests/ClockTests.swift | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/Sources/Clock.swift b/Sources/Clock.swift index fade988..ea03878 100644 --- a/Sources/Clock.swift +++ b/Sources/Clock.swift @@ -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) + } } } } diff --git a/Tests/KronosTests/ClockTests.swift b/Tests/KronosTests/ClockTests.swift index cfc7bd1..c0353b4 100644 --- a/Tests/KronosTests/ClockTests.swift +++ b/Tests/KronosTests/ClockTests.swift @@ -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) + } }