我知道我可以创建这样的后台任务:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do some task
dispatch_async(dispatch_get_main_queue(), ^{
// update some UI
});
});
(Source)
如何创建每n
秒执行代码块的后台任务,如何停止此任务?
答案 0 :(得分:16)
合并NSTimer
和您的背景代码。那将是:
- (void)someBackgroundTask:(NSTimer *)timer {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),
^{
// do some task
dispatch_async(dispatch_get_main_queue(), ^{
// update some UI
});
});
}
然后通过计时器
调用此方法NSTimer *timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(someBackgroundTask:)
userInfo:nil
repeats:YES];
停止该计时器和后台执行
[timer invalidate];
func someBackgroundTask(timer:NSTimer) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),
{ () -> Void in
println("do some background task")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
println("update some UI")
})
})
}
然后通过计时器
调用此方法var timer = NSTimer(timeInterval: 1.0,
target: self,
selector: "someBackgroundTask:",
userInfo: nil,
repeats: true)
停止该计时器和后台执行
timer.invalidate()
func someBackgroundTask(timer:Timer) {
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
print("do some background task")
DispatchQueue.main.async {
print("update some UI")
}
}
}
并创建/调用计时器为
var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
timer in
self.someBackgroundTask(timer: timer)
}
invalidate
方法相同。