8

Use Case

I have a set of processes that each need to run on their own background thread at a certain execution rate (3 times a second, once every 10 seconds etc).

I believe CFRunLoop and/or NSRunLoop provide this functionality

Question

How do I create (in swift) a new background thread for which to execute a periodic tasks on?

Community
  • 1
  • 1
Jeef
  • 26,861
  • 21
  • 78
  • 156
  • http://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift This question might help you – milo526 Oct 13 '15 at 14:14
  • This answer has one-and-done processes not loops – Jeef Oct 13 '15 at 14:16
  • Calling that with a NSTimer? http://stackoverflow.com/questions/25951980/swift-do-something-every-x-minutes – milo526 Oct 13 '15 at 14:18
  • @milo526 thanks for trying - but I'm looking specifically to start an independent background thread loop. The timer just calls in whatever thread it was called from ... (i think). – Jeef Oct 13 '15 at 14:19
  • 1
    The second answer (http://stackoverflow.com/a/25952724/2976077) does only run on a background thread. it first creates a new thread and run it every x seconds. – milo526 Oct 13 '15 at 14:24
  • Anyone asking questions on stackoverflow shouldn't use CFRunLoop. And most people answering questions here don't. – gnasher729 Jan 14 '19 at 00:44

2 Answers2

9

Old post but "background run loop" doesn't equal "background thread" nor does it mean "background queue". Usually there is only one run loop and that is the main thread's run loop. Other threads usually use this run loop but rarely have their own run loop (or their respective run loops are never readily available). To create a run loop for a thread that is not the main thread Apple has a guide and states when this should be done.

Also here is a nice guide I found on run loops in background threads.

keji
  • 5,947
  • 3
  • 31
  • 47
-1

This can be done with the Global Dispatch background queue.

Example background thread:

      let qualityServiceClass = QOS_CLASS_BACKGROUND
      let backgroundQueue = dispatch_get_global_queue(qualityServiceClass, 0)

        dispatch_async(backgroundQueue, {  
            print("This is run on the background queue")
            // With the help of NSTimer it will hit method after every 5 minutes (300 seconds).
            _ = NSTimer.scheduledTimerWithTimeInterval(300.0, target: self, selector: #selector(AppDelegate.callAppSettingWebservice), userInfo: nil, repeats: true)

        })
Efren
  • 4,003
  • 4
  • 33
  • 75
kaushal
  • 903
  • 10
  • 17