dreymonde/timers
**Intuitive Swift timers with automatic memory management**
Features
- [x] Automatically manages timers lifetime: no need to worry about memory leaks
- [x] Repeated timers
- [x] One-off timers
- [x] Timers that fire at a specific date and then repeat with a set interval
- [x] Full access to
Foundation.TimerAPIs for more complex use cases - [x] Easy to extend
- [x] Unit-tested
Installation
Swift Package Manager
- Click File → Swift Packages → Add Package Dependency.
- Enter
https://github.com/dreymonde/Timers.git
Note<br> Timers is a very simple library and only consists of one file (Timers.swift). Do not expect updates, this release is likely final. If you need additional functionality, feel free to fork or copy Timers.swift directly into your project and extend. PRs are also welcome.
Guide
All these timers are managed by the
Timersinstance and are invalidated automatically when theTimersinstance is deallocated.
Creating a Basic Repeating Timer
import Timers
final class MyViewController: UIViewController {
let timers = Timers()
override func viewDidLoad() {
super.viewDidLoad()
timers.addRepeating(timeInterval: 1.0, withTarget: self) { (self, timer) in
self.reloadData()
}
}
func reloadData() {
// reload your data here
}
}Creating a Repeating Timer with Tolerance
timers.addRepeating(timeInterval: 1.0, tolerance: 0.1, withTarget: self) { (self) in
self.reloadData()
}In this case, the timer will have a slight tolerance of 0.1 seconds which allows the system to adjust the firing of the timer for better system performance.
Creating a Timer that Fires Once at a Specific Date
let date = Date().addingTimeInterval(5) // Date 5 seconds from now
timers.fireAt(date, withTarget: self) { (self) in
self.reloadData()
}
// or:
timers.fireAfter(timeInterval: 5, withTarget: self) { (self) in
self.reloadData()
}Creating a Timer that Fires at a Specific Date and Repeats at a Set Interval
timers.addRepeating(
initiallyFireAt: Date().addingTimeInterval(10),
thenRepeatWithInterval: 5.0,
withTarget: self
) { (self, timer) in
self.reloadData()
}Creating a Timer Manually
For a more custom use case where you want to add the timer manually:
let customTimer = Timer(timeInterval: 1.0, repeats: true) { _ in
print("This is a custom timer")
}
timers.addTimerManually(timer: customTimer)Clearing All Timers
At any point if you want to stop and invalidate all timers you can call:
timers.clear()See also
- Time by @dreymonde - Type-safe time calculations in Swift, powered by generics
- DateBuilder by @dreymonde - Create dates and date components easily, of any complexity (e.g. "first Thursday of the next month")
Package Metadata
Repository: dreymonde/timers
Default branch: main
README: README.md