Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Timer in Linux

Tags:

linux

swift

timer

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

like image 872
Sergey Di Avatar asked Dec 23 '22 12:12

Sergey Di


1 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.

like image 118
Martin R Avatar answered Jan 03 '23 15:01

Martin R