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

Overview

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.

Comments
  • Include NSTimer in block?

    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()
    }
    
    opened by efremidze 7
  • Usage issue

    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)
    }
    
    opened by pjebs 3
  • is it supposed to work on a background queue?

    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

    opened by jaimeagudo 2
  • Support lower deployment targets than 10.11

    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.

    opened by jhoughjr 2
  • Use default arguments naming

    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 :)

    opened by kostiakoval 2
  • Convert code base to swift 3.0 (Xcode 8.0 beta 2)

    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.

    opened by ldiqual 1
  • Support for Swift Package Manager

    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.

    opened by janlionly 0
  • Add the ability to specify RunLoop and RunLoopMode in `after` and `every` methods

    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.

    opened by madeinqc 0
  • Can't figure out how to stop timer

    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()
            }
            
        }
    
    opened by benjam1n 0
  • Crash when calling fire() after creating timer

    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.

    opened by BenchR267 10
Releases(2.1.0)
Owner
Radek Pietruszewski
Face shield manufacturer. Software writer. Proud generalist. Poking the box since 1995. Do you even Swift? 🚀♻️
Radek Pietruszewski
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

Luo Xiu 1.8k Sep 20, 2022
Pomodoro is a macOS status bar application written in SwiftUI, which allows you to control your work and break time, exploiting the pomodoro-technique.

Pomodoro Pomodoro is a macOS status bar application which allows you to control your work and break time. Through this application you will be able to

Cristian Turetta 3 Sep 2, 2022
Remote shell using libssh2 with Objective-C, thread safe implementation.

NSRemoteShell Remote shell using libssh2 with Objective-C. Thread safe implementation. Available as Swift Package. git libssh2 prebuilt binaries are r

Lakr Aream 14 Sep 13, 2022
Egg Timer app helps you to cook your egg in the way you want

Egg Timer Egg Timer app helps you to cook your egg in the way you want. You need to decide on how do you want to eat your egg than just click the egg

Emrullah Cirit 1 Dec 15, 2021
A Swift DSL that allows concise and effective concurrency manipulation

NOTE Brisk is being mothballed due to general incompatibilities with modern version of Swift. I recommend checking out ReactiveSwift, which solves man

Jason Fieldman 25 May 24, 2019
Swift/UIKit app for time measurment

TimerApp _ About Swift/UIKit app for time measurment Features: Start/pause time count Reset timer Long press gesture on time label to reset timer Time

Ilya 1 May 28, 2022
Using async / await on iOS 13: everything you need to know

Using async / await on iOS 13: everything you need to know! ?? Content This repository contains the code sample I've used during December 14th's lives

Vincent Pradeilles 11 Feb 1, 2022
GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way

GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way. This help

Quan Vo 43 Jan 29, 2022
AsyncTimer is a precision asynchronous timer. You can also use it as a countdown timer

AsyncTimer ?? Features Can work as a countdown timer Can work as a periodic Timer Can work as a scheduled timer Working with user events (like: scroll

Adrian Bobrowski 26 Jul 6, 2022
Tools for using Swift Concurrency on macOS 10.15 Catalina, iOS 13, tvOS 13, and watchOS 6.

ConcurrencyCompatibility Tools for using Swift Concurrency on macOS 10.15 Catalina, iOS 13, tvOS 13, and watchOS 6. Xcode 13.2 adds backwards deployme

Zachary Waldowski 7 Sep 21, 2022
Demonstration of using Tasks and TaskGroup to thread a calculation.

TasksTest Demonstration of using Tasks and TaskGroup to thread a calculation. The calculation takes place in a separate Swift class that can be reused

null 0 Dec 27, 2021
An introduction to using Swift's new concurrency features in SwiftUI

SwiftUI Concurrency Essentials An introduction to using Swift's new concurrency features in SwiftUI Discuss with me · Report Bug · Request Feature Art

Peter Friese 71 Sep 16, 2022
Resume-app - A simple iOS app to showcase Swift development skills using Xcode

resume-app A simple iOS app to showcase Swift development skills using Xcode. Pr

AJ Rivera 0 Jan 12, 2022
Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.

Venice provides structured concurrency and CSP for Swift. Features Coroutines Coroutine cancelation Coroutine groups Channels Receive-only chan

Zewo 1.5k Aug 28, 2022
Make your logic flow and data flow clean and human readable

Flow What's Flow Flow is an utility/ design pattern that help developers to write simple and readable code. There are two main concerns: Flow of opera

null 18 Jun 17, 2022
Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.

CollectionConcurrencyKit Welcome to CollectionConcurrencyKit, a lightweight Swift package that adds asynchronous and concurrent versions of the standa

John Sundell 646 Sep 17, 2022
Extensions and additions to AsyncSequence, AsyncStream and AsyncThrowingStream.

Asynchone Extensions and additions to AsyncSequence, AsyncStream and AsyncThrowingStream. Requirements iOS 15.0+ macOS 12.0+ Installation Swift Packag

Red Davis 69 Sep 22, 2022
straightforward networking and error handling with async-await and URLSession

AsyncAwaitNetworkingPlayground How To Run Just clone the project, open it and run. Some notes about AsyncAwaitNetworkingPlayground It's a straightforw

Fırat Yenidünya 15 Jul 26, 2022
Slack message generator and API client, written in Swift with Result Builders and Concurrency

Slack Message Client This package provides a Swift object model for a Slack Block Kit message, as well as a Result Builder convenience interface for e

Mike Lewis 2 Jul 30, 2022