Combine NSTimer and your background code. It will look like this:
Objective-c
- (void)someBackgroundTask:(NSTimer *)timer { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
and then call this method with a timer
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(someBackgroundTask:) userInfo:nil repeats:YES];
to stop this timer and background execution
[timer invalidate]
Swift 2.2
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 with a timer
var timer = NSTimer(timeInterval: 1.0, target: self, selector: "someBackgroundTask:", userInfo: nil, repeats: true)
to stop this timer and background execution
timer.invalidate()
Swift 3 and later
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 / call a timer like
var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in self.someBackgroundTask(timer: timer) }
invalidate method is the same.
x4h1d source share