Swift Timer in Linux

Viewed 1019

Could you please help, how to use Timer instance in Swift 4 on Linux Ubuntu 16.04?

When I try to do:

let timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(MyClass.myMethod), userInfo: nil, repeats: true)

I got error: error: '#selector' can only be used with the Objective-C runtime

2 Answers

You can use the block-based timer functions on Linux. Here is a minimal self-contained example which compiles and runs both in Xcode 9.1 and on https://swift.sandbox.bluemix.net/#/repl:

import Foundation
import CoreFoundation

let timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { timer in
    print("In timer function")
    exit(0)
}

CFRunLoopRun()

(I added the exit(0) only because the IBM Swift Sandbox limits the program execution time to 5 seconds.)

Alternatively, use a DispatchSourceTimer as demonstrated here.

Thanks to @Martin R, I got the final code for Swift 4 on Ubuntu 16.04:

import Foundation
import Dispatch

class MyClassWithTimer {

  var timer: DispatchSourceTimer?

  init() {
    startTimer()
  }

  func startTimer() {
    let queue = DispatchQueue(label: "com.domain.app.timer")
    timer = DispatchSource.makeTimerSource(queue: queue)
    timer?.schedule(deadline: .now(), repeating: 2.0, leeway: .seconds(0))
    timer?.setEventHandler { [weak self] in
        print("Execute timer action")
        self?.timerAction()
    }
    timer?.resume()
  }

  func timerAction() {
    print("Do something")
  }

  func stopTimer() {
      timer?.cancel()
      timer = nil
  }

  deinit {
      self.stopTimer()
  }
}
Related