有没有办法在循环中使用dispatch_after
?我有下面的延迟功能:
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
我想在这样的循环中执行它:
while true {
self.delay(1.0) {
// Do something repeatedly
}
}
但我似乎无法让它发挥作用。有可能这样做吗?
答案 0 :(得分:1)
使用计时器类型的调度源重复调用闭包。例如:
import Cocoa
import XCPlayground
func withTimerInterval(seconds: NSTimeInterval, block: dispatch_block_t) -> dispatch_source_t {
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
let interval = Int64(seconds * NSTimeInterval(NSEC_PER_SEC))
dispatch_source_set_timer(source, dispatch_time(DISPATCH_TIME_NOW, interval), UInt64(interval), 20 * NSEC_PER_MSEC)
dispatch_source_set_event_handler(source, block)
dispatch_resume(source)
return source
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let timer = withTimerInterval(1) {
print("hello again")
}
取消这样的计时器:
dispatch_source_cancel(timer)
答案 1 :(得分:0)
for (;;sleep(1)) {
print("Hello Again");
}
*注意,这将每隔1秒钟(1秒+ 1个周期)锁定主线程1秒钟。如果这是一个问题,请在一个单独的线程中运行 while for循环,改为睡眠NSThread,并在for循环中简单地dispatch_get_main_queue()
。