Created
January 20, 2017 00:07
-
-
Save brennanMKE/5c1cdc716d62a76675db2cf36422cde0 to your computer and use it in GitHub Desktop.
Task Scheduler with Swift 2.3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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