Skip to content

Commit

Permalink
Add asyncPeriodically DispatchQueue extension
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkenso committed Sep 20, 2024
1 parent 5ef4ca2 commit d174704
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,31 @@ extension DispatchQueue {
delay: TimeInterval,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void
execute work: @escaping () -> Void
) {
asyncAfter(deadline: .now() + delay, qos: qos, flags: flags, execute: work)
}

public func asyncAfter(delay: TimeInterval, execute: DispatchWorkItem) {
asyncAfter(deadline: .now() + delay, execute: execute)
}

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

extension DispatchQueue {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import SpellbookFoundation

import Foundation
import XCTest

class DispatchQueueExtensionsTests: XCTestCase {
func test_asyncPeriodically() {
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()
return count < limit
}
Thread.sleep(forTimeInterval: 0.1)
XCTAssertEqual(count, limit)
waitForExpectations()
}
}

0 comments on commit d174704

Please sign in to comment.