Swifty API for NSTimer

Last update: Aug 4, 2022

SwiftyTimer

Platforms CI Status CocoaPods Carthage compatible Swift version

Modern Swifty API for NSTimer

SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It's time to get rid of Objective-C cruft.

Read Swifty APIs: NSTimer for more information about this project.

Usage

You can easily schedule repeating and non-repeating timers (repeats and delays) using Timer.every and Timer.after:

Timer.every(0.7.seconds) {
    statusItem.blink()
}

Timer.after(1.minute) {
    println("Are you still here?")
}

You can specify time intervals with these intuitive helpers:

100.ms
1.second
2.5.seconds
5.seconds
10.minutes
1.hour
2.days

You can pass method references instead of closures:

Timer.every(30.seconds, align)

Manual scheduling

If you want to make a timer object without scheduling, use new(after:) and new(every:):

let timer = Timer.new(every: 1.second) {
    println(self.status)
}

(This should be defined as an initializer, but a bug in Foundation prevents this)

Call start() to schedule timers created using new. You can optionally pass the run loop and run loop modes:

timer.start()
timer.start(modes: .defaultRunLoopMode, .eventTrackingRunLoopMode)

Invalidation

If you want to invalidate a repeating timer on some condition, you can take a Timer argument in the closure you pass in:

Timer.every(5.seconds) { (timer: Timer) in
    // do something
    
    if finished {
        timer.invalidate()
    }
}

Installation

Note: If you're running Swift 2, use SwiftyTimer v1.4.1

CocoaPods

If you're using CocoaPods, just add this line to your Podfile:

pod 'SwiftyTimer'

Install by running this command in your terminal:

pod install

Then import the library in all files where you use it:

import SwiftyTimer

Carthage

Just add to your Cartfile:

github "radex/SwiftyTimer"

Manually

Simply copy Sources/SwiftyTimer.swift to your Xcode project.

More like this

If you like SwiftyTimer, check out SwiftyUserDefaults, which applies the same swifty approach to NSUserDefaults.

You might also be interested in my blog posts which explain the design process behind those libraries:

Contributing

If you have comments, complaints or ideas for improvements, feel free to open an issue or a pull request.

Author and license

Radek Pietruszewski

SwiftyTimer is available under the MIT license. See the LICENSE file for more info.

GitHub

https://github.com/radex/SwiftyTimer
Comments
  • 1. Include NSTimer in block?

    What are your thoughts about including the timer object in the block?

    public class func every(interval: NSTimeInterval, _ block: NSTimer -> Void) -> NSTimer {}
    

    Otherwise I need to declare the variable separately like this:

    var timer: NSTimer?
    timer = NSTimer.every(5.seconds) {
        timer?.invalidate()
    }
    
    Reviewed by efremidze at 2016-02-09 01:29
  • 2. Usage issue

    I was wondering if you can clarify what the difference is between

    NSTimer.every(0.7.seconds) {
        println(self.status)
    }
    

    and

    let timer = NSTimer.new(every: 1.second) {
        println(self.status)
    }
    
    Reviewed by pjebs at 2016-11-15 12:03
  • 3. is it supposed to work on a background queue?

    Thanks for sharing your work. Trying to do something apparently simple but I see nothing on the console and breakpoints don't stop there. What am I getting wrong?

    let backgroundQueue = DispatchQueue(label: "1sec",
        qos: .background,
        target: nil)
    
    backgroundQueue.async {
        Timer.every(1.seconds) {
            self.log.debug("Timer tick at \(Date())")
        }
    }
    

    Cheers

    Reviewed by jaimeagudo at 2017-01-03 11:33
  • 4. Support lower deployment targets than 10.11

    I haven't perused the source fully, but I would imagine there is no reason that 10.11 is the deployment target for this. I'm wanting to use it in a project that needs to support mavericks. My guess is it was an oversight, as it was in my project file.

    Reviewed by jhoughjr at 2016-03-18 16:49
  • 5. Use default arguments naming

    When I call a NSTimer.after and pass a function, it doesn't have a argument name for second argument. This feels not natural for me regarding that all other functions usually used default or external names.

      NSTimer.after(1.second, close)
    

    Using default names don't change the nice trailing closure syntax

    public class func after(interval: NSTimeInterval, block: () -> Void) -> NSTimer 
    ...
    NSTimer.after(1.second) {
      print("done")
    }
    

    If you agree I can make a PR :)

    Reviewed by kostiakoval at 2015-09-08 10:52
  • 6. Convert code base to swift 3.0 (Xcode 8.0 beta 2)

    @radex

    Fixes https://github.com/radex/SwiftyTimer/issues/27

    Most of the migration was done using Xcode's migration tool. It is mostly about renaming NSTimer to Timer.

    Minor thing to note: Swift 3 will now produce a warning of the result of Timer.<method> is unused.

    Let me know if you have any question.

    Reviewed by ldiqual at 2016-07-11 01:33
  • 7. Support for Swift Package Manager

    Swift Package Manager

    • iOS: Open Xcode, File->Swift Packages, search input https://github.com/radex/SwiftyTimer.git, and then select Version Up to Next Major 2.1.1 < .
    • Or add dependencies in your Package.swift:
    .package(url: "https://github.com/radex/SwiftyTimer.git", .upToNextMajor(from: "2.1.1")),
    

    Please git a new tag to support it.

    Reviewed by janlionly at 2020-06-29 08:19
  • 8. Add the ability to specify RunLoop and RunLoopMode in `after` and `every` methods

    This was required in my project to be able to use after and every methods for timers that need to update the UI. The timer needs to run in .commonModes to be able to update the UI while scrolling.

    It keep the same behaviour as previously and the signature is backward compatible. I added a new start function because the splat operator is not available in Swift, hence the need to create a new one that takes an array as parameters.

    Feedbacks are welcome, I will adjust the PR accordingly.

    Reviewed by madeinqc at 2017-08-08 14:53
  • 9. Can't figure out how to stop timer

    Hello!

    I want to make a function that starts the timer unless there is a bool true in params (e.g. animateStatusIcon(stop: true)) - in that case I want to stop the timer. Does anyone have an idea what's going on here?

    The timer starts but no matter what I do it wont stop.

    func animateStatusIcon(stop: Bool? = nil){
            
            let icon = NSImage(named: "statusIcon")
            let iconActive = NSImage(named: "statusIconActive")
            
            let timer = Timer.every(0.4.seconds) {
                self.statusItem.image = icon
                Timer.after(0.2.seconds) {
                    self.statusItem.image = iconActive
                }
            }
                
            if(stop == true){
                print(stop!)
                print("should stop now")
                timer.invalidate()
            } else  {
                print(stop)
                print("start")
                timer.start()
            }
            
        }
    
    Reviewed by benjam1n at 2017-05-10 15:53
  • 10. Crash when calling fire() after creating timer

    The following code worked with 1.3.0 but crashes with 1.4.0:

    let timer = NSTimer.every(1) { 
                print("do something!")
            }
    timer.fire()
    

    The internal refactoring of not using NSTimer initializers might be the problem.

    Reviewed by BenchR267 at 2016-07-22 09:15
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jun 18, 2022
Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)
Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)

Schedule(简体中文) Schedule is a timing tasks scheduler written in Swift. It allows you run timing tasks with elegant and intuitive syntax. Features Elega

Aug 6, 2022
Typical master detail SAMPLE application written in Swift to test NY Times Most Popular API
Typical master detail SAMPLE application written in Swift to test NY Times Most Popular API

NYTimes-Demo: Typical master detail SAMPLE application written in Swift to test NY Times Most Popular API. This SAMPLE application is written in Swift

Nov 3, 2021
NasaApod - iOS, Swift, MVVM, Consuming NASA Astronomy Picture of the Day API for any selected date

NasaApod iOS, Swift, MVVM, Unit Tests Consuming NASA Astronomy Picture of the Da

Jan 10, 2022
A swift wrapper for NSTimer

Every.Swift - A Convenient NSTimer Wrapper Usage Provided that your class implement TimerManageable protocol you just do: self.every(3.seconds) {

Apr 14, 2022
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jun 18, 2022
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jun 18, 2022
A Swifty API for attributed strings

SwiftyAttributes A Swifty API for attributed strings. With SwiftyAttributes, you can create attributed strings like so: let fancyString = "Hello World

Aug 7, 2022
Github API V3 Swifty Wrapper

GithubPilot - Github API V3 Swifty Wrapper This is a Swift Github API Wrapper, it could make your life a little easier if you want to make an App with

Feb 2, 2022
A Swifty API for global macOS hotkeys.

A Swifty API for global macOS hotkeys. Install Add the following dependency to your Package.swift file: .package(url: "https://github.com/jordanbaird/

Jun 27, 2022
Swifty and modern UserDefaults

Defaults Swifty and modern UserDefaults Store key-value pairs persistently across launches of your app. It uses NSUserDefaults underneath but exposes

Aug 3, 2022
The most swifty way to deal with XML data in swift 5.

SwiftyXML SwiftyXML use most swifty way to deal with XML data. Features Infinity subscript dynamicMemberLookup Support (use $ started string to subscr

Jul 26, 2022
A sweet and swifty YAML parser built on LibYAML.
A sweet and swifty YAML parser built on LibYAML.

Yams A sweet and swifty YAML parser built on LibYAML. Installation Building Yams requires Xcode 11.x or a Swift 5.1+ toolchain with the Swift Package

Aug 2, 2022
Fashion is your helper to share and reuse UI styles in a Swifty way.
Fashion is your helper to share and reuse UI styles in a Swifty way.

Fashion is your helper to share and reuse UI styles in a Swifty way. The main goal is not to style your native apps in CSS, but use a set

Aug 7, 2022
Swifty, modern UIAlertController wrapper.
Swifty, modern UIAlertController wrapper.

Alertift Alertift.alert(title: "Alertift", message: "Alertift is swifty, modern, and awesome UIAlertController wrapper.") .action(.default("❤️"))

Jul 26, 2022
🍞 Loaf is a Swifty Framework for Easy iOS Toasts
🍞 Loaf is a Swifty Framework for Easy iOS Toasts

Loaf ?? Inspired by Android's Toast, Loaf is a Swifty Framework for Easy iOS Toasts Usage From any view controller, a Loaf can be presented by calling

Aug 1, 2022
Swifty closures for UIKit and Foundation
Swifty closures for UIKit and Foundation

Closures is an iOS Framework that adds closure handlers to many of the popular UIKit and Foundation classes. Although this framework is a substitute f

Jul 31, 2022
A swifty iOS framework that allows developers to create beautiful onboarding experiences.
A swifty iOS framework that allows developers to create beautiful onboarding experiences.

SwiftyOnboard is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial SwiftyOnboard A simp

Aug 3, 2022
Swifty regular expressions

Regex Swifty regular expressions This is a wrapper for NSRegularExpression that makes it more convenient and type-safe to use regular expressions in S

Aug 2, 2022
Swifty TVML template manager with or without client-server

TVMLKitchen ?? ?? TVMLKitchen helps to manage your TVML with or without additional client-server. Requirements Swift3.0 tvOS 9.0+ Use 0.9.6 for Swift2

Mar 1, 2022