在Swift中每x分钟做一件事
我怎样才能每分钟运行一个function? 在JavaScript中我可以做类似setInterval
事情,Swift中是否存在类似的东西?
通缉输出:
Hello World每分钟一次…
var helloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: Selector("sayHello"), userInfo: nil, repeats: true) func sayHello() { NSLog("hello World") }
记得导入基金会。
Swift 3:
var helloWorldTimer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(ViewController.sayHello), userInfo: nil, repeats: true) func sayHello() { NSLog("hello World") }
在Swift 3中,你可以创build一个Timer
。 如果目标iOS版本为10或更高,则可以使用基于块的格式,从而简化潜在的强参考周期,例如:
weak var timer: Timer? func startTimer() { timer?.invalidate() // just in case you had existing `Timer`, `invalidate` it before we lose our reference to it timer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in // do something here } } func stopTimer() { timer?.invalidate() } // if appropriate, make sure to stop your timer in `deinit` deinit { stopTimer() }
在Swift 2中,你创build了一个NSTimer
。 如果你使用的是Swift 2,你可能会使用10.0之前的iOS版本,在这种情况下,你必须使用旧的target
/ selector
模式:
weak var timer: NSTimer? func startTimer() { timer?.invalidate() // just in case you had existing `NSTimer`, `invalidate` it before we lose our reference to it timer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: #selector(handleTimer(_:)), userInfo: nil, repeats: true) } func handleTimer(timer: NSTimer) { // do something here } func stopTimer() { timer?.invalidate() } // because this old target/selector approach will keep a strong reference // to the `target`, if you want the timer to stop when the view controller // is dismissed, you can't stop the timer in `deinit`, but rather have to // detect the dismissing of the view controller using other mechanisms. Commonly, // we used to detect the view disappearing, like below: override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) stopTimer() }
虽然NSTimer
通常是最好的,为了完整起见,我应该注意到,你也可以使用dispatch timer,这对调度后台线程的定时器很有用。 使用调度定时器,因为它们是基于块的,所以只要使用weak
引用,它就避免了NSTimer
旧的target
/ selector
模式带来的一些强烈的参考周期挑战。
所以,在Swift 3:
var timer: DispatchSourceTimer? func startTimer() { let queue = DispatchQueue(label: "com.domain.app.timer") // you can also use `DispatchQueue.main`, if you want timer = DispatchSource.makeTimerSource(queue: queue) timer!.scheduleRepeating(deadline: .now(), interval: .seconds(60)) timer!.setEventHandler { [weak self] in // do whatever you want here } timer!.resume() } func stopTimer() { timer?.cancel() timer = nil } deinit { self.stopTimer() }
在Swift 2中:
var timer: dispatch_source_t? func startTimer() { let queue = dispatch_queue_create("com.domain.app.timer", nil) // again, you can use `dispatch_get_main_queue()` if you want to use the main queue timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) dispatch_source_set_timer(timer!, DISPATCH_TIME_NOW, 60 * NSEC_PER_SEC, 1 * NSEC_PER_SEC) // every 60 seconds, with leeway of 1 second dispatch_source_set_event_handler(timer!) { [weak self] in // do whatever you want here } dispatch_resume(timer!) } func stopTimer() { if let timer = timer { dispatch_source_cancel(timer) self.timer = nil } } deinit { self.stopTimer() }
有关更多信息,请参见并发编程指南的Dispatch Sources部分中的Dispatch Source示例的Creating a Timer部分。
你可以使用NSTimer
var timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("function"), userInfo: nil, repeats: true)
在select器()你把你的函数名称
下面是Swift 3(其中NSTimer
重命名为Timer
)的NSTimer
答案的更新,使用闭包而不是命名函数:
var timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { (_) in print("Hello world") }
在3.0版本中,GCD得到了重构:
let timer : DispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) timer.scheduleRepeating(deadline: .now(), interval: .seconds(60)) timer.setEventHandler { NSLog("Hello World") } timer.resume()
这对于需要在特定队列上分派时特别有用。 另外,如果您打算将其用于用户界面更新,则build议您查看CADisplayLink
因为它与GPU刷新率同步。