How can I run a function every minute?
In JavaScript I can do something like setInterval
, does something similar exist in Swift?
Wanted output:
Hello World once a minute...
How can I run a function every minute?
In JavaScript I can do something like setInterval
, does something similar exist in Swift?
Wanted output:
Hello World once a minute...
If you can allow for some time drift here's a simple solution executing some code every minute:
Just run
executeRepeatedly()
once and it'll be executed every minute. The execution stops when the owning object (self
) is released. You also can use a flag to indicate that the execution must stop.In swift 3.0 the GCD got refactored:
This is specially useful for when you need to dispatch on a particular Queue. Also, if you're planning on using this for user interface updating, I suggest looking into
CADisplayLink
as it's synchronized with the GPU refresh rate.Remember to import Foundation.
Swift 4:
You can use
NSTimer
In selector() you put in your function name
In Swift 3, you can create a
Timer
. And if targeting iOS version 10 and greater, you can use the block-based rendition, which simplifies the potential strong reference cycles, e.g.:In Swift 2, you create a
NSTimer
. And if you're using Swift 2, you may well be using iOS version prior to 10.0, in which case you have to use the oldertarget
/selector
pattern:While
NSTimer
is generally best, for the sake of completeness, I should note that you can also use dispatch timer, which is useful for scheduling timers on background threads. With dispatch timers, since they're block-based, it avoids some of the strong reference cycle challenges with the oldtarget
/selector
pattern ofNSTimer
, as long as you useweak
references.So, in Swift 3:
In Swift 2:
For more information, see the the Creating a Timer section of Dispatch Source Examples in the Dispatch Sources section of the Concurrency Programming Guide.
Here's an update to the
NSTimer
answer, for Swift 3 (in whichNSTimer
was renamed toTimer
) using a closure rather than a named function: