Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Kirill Titov committed Aug 11, 2017
1 parent 349ffd4 commit 27af67e
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ delay(by: .seconds(5), dispatchLevel: .userInteractive) {
}
```

#### every(_ interval:) { ... }
Runs a given closure every interval. Dispatch queue can be set optionally (as well as QoS and allowed leeway, see definition)
``` Swift
var counter = 0
let timer = every(.milliseconds(10)) {
counter += 1
print("I've been executed \(counter) times")
}
sleep(3)
timer.cancel() // you must stop the execution manually (otherwise you may end up with zombie processes when killing the app manually), note that this cannot be done inside a closure
```

### IntExtension

#### init(randomBelow:)
Expand Down
23 changes: 23 additions & 0 deletions Sources/Globals.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,26 @@ public func delay(by delayTime: Timespan, qosClass: DispatchQoS.QoSClass? = nil,
let dispatchQueue = qosClass != nil ? DispatchQueue.global(qos: qosClass!) : DispatchQueue.main
dispatchQueue.asyncAfter(deadline: DispatchTime.now() + delayTime, execute: closure)
}

/// Executes passed closure every Timespan interval.
///
/// - Parameters:
/// - interval: Execution interval duration
/// - queue: Dispatch queue for execution. Defaults to global
/// - qos: Quality of service. Defaults to .default
/// - leeway: Allowed leeway between executions. Defaults to .milliseconds(10)
/// - closure: Block of code to run
/// - Returns: Timer object
public func every(
_ interval: Timespan,
queue: DispatchQueue = DispatchQueue.global(),
qos: DispatchQoS = .default,
leeway: DispatchTimeInterval = .milliseconds(10),
_ closure: @escaping DispatchSourceProtocol.DispatchSourceHandler
) -> DispatchSourceTimer {
let timer = DispatchSource.makeTimerSource(queue: queue)
timer.setEventHandler(qos: qos, handler: closure)
timer.scheduleRepeating(deadline: .now(), interval: interval, leeway: leeway)
timer.resume()
return timer
}
14 changes: 14 additions & 0 deletions Tests/GlobalsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,18 @@ class GlobalsTests: XCTestCase {

waitForExpectations(timeout: delayTime + 1.0, handler: nil)
}

func testEvery() {
let expectation = self.expectation(description: "Wait for three executions.")
var counter = 0
let timer = every(.milliseconds(10)) {
counter += 1
if counter >= 3 {
expectation.fulfill()
}
}
waitForExpectations(timeout: 2) { error in
timer.cancel()
}
}
}

0 comments on commit 27af67e

Please sign in to comment.