Created
December 6, 2016 08:03
-
-
Save networkextension/dc2ba36115f04c281bfb787397ee359c to your computer and use it in GitHub Desktop.
Swift3 DispatchSourceTimer
This file contains hidden or 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
| //: Playground - noun: a place where people can play | |
| import Cocoa | |
| var str = "Hello, playground" | |
| import Foundation | |
| import Dispatch | |
| func test(){ | |
| for _ in 1..<5 { | |
| print("\(Date()) Hello, World!") | |
| } | |
| } | |
| class testclass{ | |
| typealias qblock = ((DispatchSourceTimer) ->Void) | |
| let call:qblock | |
| var dispatch_timer:DispatchSourceTimer | |
| let q :DispatchQueue | |
| init(c:@escaping qblock) { | |
| call = c | |
| q = DispatchQueue(label:"com.fb.interview") | |
| self.dispatch_timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags.init(rawValue: 0), queue:q ) | |
| q.async{ | |
| let interval: Double = 1.0 | |
| let delay = DispatchTime.now() | |
| self.dispatch_timer.scheduleRepeating(deadline: delay, interval: interval, leeway: .nanoseconds(0)) | |
| self.dispatch_timer.setEventHandler { | |
| self.call(self.dispatch_timer) | |
| } | |
| self.dispatch_timer.setCancelHandler { | |
| print("dispatch_timer cancel") | |
| } | |
| self.dispatch_timer.resume() | |
| } | |
| } | |
| func resume() { | |
| q.async { | |
| self.dispatch_timer.resume() | |
| } | |
| } | |
| } | |
| var begin = Date() | |
| class FBClass{ | |
| var fbTimer:testclass | |
| init(){ | |
| fbTimer = testclass.init {(t:DispatchSourceTimer) in | |
| if Date().timeIntervalSince(begin) > 10{ | |
| print(t.suspend()) | |
| print("\(Date()) cancel") | |
| begin = Date() | |
| return | |
| } | |
| print("\(Date()) working") | |
| } | |
| } | |
| func resume() { | |
| fbTimer.dispatch_timer.resume() | |
| } | |
| } | |
| let fbTest = FBClass() | |
| for i in 0...50 { | |
| //main don't exit | |
| sleep(1) | |
| if i == 15 { | |
| fbTest.resume() | |
| } | |
| //usleep(5000) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment