我尝试使用dispatch_time定期以600秒的间隔递归调用doTask()
。这是我的简单代码:
private func doTask() -> Void {
var interval : NSTimeInterval = someService.getInterval() //it is 600
NSLog("interval = \(interval)"); //Like I said, it is 600, because I see the log
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC)))
//recursively call doTask() after 600 seconds
dispatch_after(dispatchTime,
GlobalBackgroundQueue,
{self.doTask()}
)
}
以下是GlobalBackgroundQueue
:
var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0)
}
但是当我在运行时调用doTask()
函数时,每次调用doTask()之间的间隔为15秒。为什么?为什么间隔不是600秒?
===== UPDATE =====
我也试过NSTimer:
NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "doTask", userInfo: nil, repeats: true)
但是在运行时,doTask()每20秒调用一次。还不是600秒。
答案 0 :(得分:0)
试试这个
let delay: UInt64 = 600
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * NSEC_PER_SEC))
答案 1 :(得分:0)
这有效:
let delay: NSTimeInterval = 600
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * delay))
dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
})