Make a service call at regular intervals in quick

I am new to fast programming and I don’t know how to call a method at regular intervals. I have a demo application for calling a service, but I don’t know how I can call it at regular intervals.

+4
source share
3 answers

You can create an NSTimer () object and call the function for a certain period of time, for example:

var updateTimer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: "callFunction", userInfo: nil, repeats: true)

this will call callFunction () every 15 seconds.

func callFunction(){
    print("function called")
}
+14
source

Here is a simple example with start and stop functions:

private let kTimeoutInSeconds:NSTimeInterval = 60

private var timer: NSTimer?

func startFetching() {
  self.timer = NSTimer.scheduledTimerWithTimeInterval(kTimeoutInSeconds,
    target:self,
    selector:Selector("fetch"),
    userInfo:nil,
    repeats:true)
}

func stopFetching() {
  self.timer!.invalidate()
}

func fetch() {
  println("Fetch called!")
}

unrecognized selector, , , NSObject, !

+5

(iOS 10, Swift 4)

let timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { (timer) in
    print("I am called every 5 seconds")

}

Remember to call the method invalidate

timer.invalidate()

GCD approach (will tend to drift a bit later with time)

func repeatMeWithGCD() {
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) {
        print("I am called every 5 seconds")

        self.repeatMeWithGCD()//recursive call
    }
}

Remember to create a return condition to prevent stackoverflow error

+1
source

All Articles