Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Created January 20, 2017 00:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brennanMKE/5c1cdc716d62a76675db2cf36422cde0 to your computer and use it in GitHub Desktop.
Save brennanMKE/5c1cdc716d62a76675db2cf36422cde0 to your computer and use it in GitHub Desktop.
Task Scheduler with Swift 2.3
public class TaskScheduler: NSObject {
weak var timer: NSTimer? = nil
var task: ((NSTimer) -> Void)?
public func schedule(interval: NSTimeInterval, repeats: Bool, task: ((NSTimer) -> Void)? = nil) -> NSTimer? {
if !NSThread.isMainThread() {
return nil
}
self.task = task
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: #selector(tick(_:)), userInfo: nil, repeats: repeats)
return timer
}
public func tick(timer: NSTimer) {
task?(timer)
}
}
import XCTest
import MyApp
class TaskSchedulerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTaskScheduler() {
let expectation = self.expectationWithDescription("Timer")
var count: Int = 0
let taskScheduler = TaskScheduler()
let timer = taskScheduler.schedule(0.25, repeats: true) { timer in
count += 1
if count == 5 {
timer.invalidate()
expectation.fulfill()
}
}
XCTAssertNotNil(timer)
let timeout: NSTimeInterval = 5
self.waitForExpectationsWithTimeout(timeout) { (error) in
if let error = error {
print("Error: \(error)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment