I know that I can create a background task like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do some task
dispatch_async(dispatch_get_main_queue(), ^{
// update some UI
});
});
(Source)
How can I create a background task which executes a code block every n
seconds and how can I stop this task?
Combine NSTimer
and your background code. That will be like:
- (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
});
});
}
and then call this method through timer
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(someBackgroundTask:)
userInfo:nil
repeats:YES];
to stop that timer and the background execution
[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")
})
})
}
and then call this method through timer
var timer = NSTimer(timeInterval: 1.0,
target: self,
selector: "someBackgroundTask:",
userInfo: nil,
repeats: true)
to stop that timer and the background execution
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")
}
}
}
and create/invoke timer as
var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
timer in
self.someBackgroundTask(timer: timer)
}
invalidate
method is same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With