Home > Mobile >  Swift Run the block of Timer without timer in first time
Swift Run the block of Timer without timer in first time

Time:03-08

I created a timer and set it to repeat every 30 seconds the timer waits 30 seconds to run the first time, then another 30 seconds for the second time, I wanted it to run the first time without the 30 seconds, is there any way?

Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { timer in
            if iteration >= 0 {
            runCommands()
            iteration -= 1
            if iteration == 0 {exit(0)}
        }
    }

CodePudding user response:

Just call fire. It does what the name implies.

Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { timer in
    if iteration >= 0 {
        runCommands()
        iteration -= 1
        if iteration == 0 {exit(0)}
    }
}.fire()

CodePudding user response:

The problem is that you have no reference to your timer. Make one!

let timer = Timer.scheduledTimer...

Now in the next line you can say timer.fire(). This causes the timer to execute its block immediately.

CodePudding user response:

Either refactor the code that's called from the timer closure to be a function, or put the closure into a variable. Then invoke the function/closure explicitly:

typealias TimerClosure = (_: Timer?) -> Void

let timerClosure: TimerClosure = { [weak self] timer in
    guard let self = self else { return }
    if self.iteration >= 0 {
        self.runCommands()
        self.iteration -= 1
        if self.iteration == 0 {exit(0)}
    }
}
Timer.scheduledTimer(withTimeInterval: 30, repeats: true, block: timerClosure )
timerClosure(nil)

}

Edit:

The approach above will work, but as others pointed out, you can also call fire() on your timer manually.

I'll leave the above part of the answer since it shows how to set up a local variable containing a closure and then both pass it to a function and call it directly, but that's not really needed here. Instead, just do this:

let timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] timer in
    guard let self = self else { return }
    if self.iteration >= 0 {
        self.runCommands()
        self.iteration -= 1
        if self.iteration == 0 { exit(0) }
    }
}
timer.fire()
  • Related