Coding4Life
Coding4Life

Reputation: 639

Loops and Dispatch Queue

I have a dispatch queue which has to be run infinitely. So am trying to have it in a do while loop so that the thread runs continuously, but when I tried to do it, I get a blank screen.

Below is the code:

    var i = 1
    do{
    dispatch.main(3)
    {
       self.myfunction()
    }
    i+=1
    }while(i>0)

I do not understand, why is it happening? and any idea on how to get a dispatch called every few seconds?

Upvotes: 1

Views: 529

Answers (1)

Sweeper
Sweeper

Reputation: 271185

Here is an extension of NSTimer, from EZSwiftExtensions.

extension NSTimer {
    public static func runThisEvery(seconds seconds: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
        let fireDate = CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
}

What the code does is easy to understand. Create a run loop timer, add it to the run loop so it can actually run and fire, and return that instance so you can stop it later.

let timer = NSTimer.runThisEvery(seconds: 3) { _ in self.myFunction() }

to stop it, just:

timer.invalidate()

Upvotes: 1

Related Questions