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) }
}
}
3
Answers
Just call
fire
. It does what the name implies.The problem is that you have no reference to your timer. Make one!
Now in the next line you can say
timer.fire()
. This causes the timer to execute its block immediately.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:
}
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: