Skip to content

Commit

Permalink
Add callback-oriented version of asyncPeriodically
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkenso committed Dec 15, 2024
1 parent 8cc9e10 commit 345fe4c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,23 @@ extension DispatchQueue {
}
schedule(firstRun: true)
}

public func asyncPeriodically(
interval: TimeInterval,
immediately: Bool,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute: @escaping (@escaping () -> Void) -> Void
) {
func schedule(firstRun: Bool) {
asyncAfter(delay: (firstRun && immediately) ? 0 : interval, qos: qos, flags: flags) {
execute {
schedule(firstRun: false)
}
}
}
schedule(firstRun: true)
}
}

extension DispatchQueue {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,21 @@ class DispatchQueueExtensionsTests: XCTestCase {
XCTAssertEqual(count, limit)
waitForExpectations()
}

func test_asyncPeriodically_async() {
var count: Int = 0
let limit = 5
let exp = expectation(description: "Repeated action")
exp.expectedFulfillmentCount = limit
DispatchQueue.global().asyncPeriodically(interval: 0.01, immediately: true) {
count += 1
exp.fulfill()
if count < limit {
$0()
}
}
Thread.sleep(forTimeInterval: 0.1 * Self.waitRate)
XCTAssertEqual(count, limit)
waitForExpectations()
}
}

0 comments on commit 345fe4c

Please sign in to comment.