Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Background Task as Loop in Swift

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?

like image 387
confile Avatar asked Apr 10 '15 12:04

confile


1 Answers

Combine NSTimer and your background code. That will be like:


Objective-C

- (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];


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 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()

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/invoke timer as

var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { 
              timer in

              self.someBackgroundTask(timer: timer)
            }

invalidate method is same.

like image 51
x4h1d Avatar answered Sep 28 '22 12:09

x4h1d