I am trying to make an application in Swift on my Ubuntu (Ubuntu 15.10 wily, Swift swift-3.0.1-RELEASE) using the Perfectlibrary .
I would like to have a function called every X seconds. For this, I use the module class : TimerFoundation
class MyTimer {
init() {
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:
}
@objc func onTimer(timer: Timer) {
print("MyTimer.onTimer")
}
}
Despite searching for several solutions with this code, compilation failed:
$> swift build
Compile Swift Module 'my-app' (7 sources)
/home/.../Sources/MyTimer.swift:8:16: error: method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C
@objc func onTimer(timer: Timer) {
Another compilation error if I extend my class from NSObjector if I removed the argument Timer:
$> swift build
Compile Swift Module 'my-app' (7 sources)
/home/.../Sources/MyTimer.swift:6:83: error: '#selector' can only be used with the Objective-C runtime
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:
I tried using another declaration that does not use selectors:
class MyTimer {
init() {
print("MyTimer.init")
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
timer in
print("MyTimer.onTimer")
}
}
}
Compilation works, but my second fingerprint is never called. I also tried manually adding my timer to the current one RunLoop:
class MyTimer {
init() {
print("MyTimer.init")
var timer = Timer(timeInterval: 1, repeats: true) {
timer in
print("MyTimer.onTimer")
}
RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
}
}
( timer.fire() ). :
class MyTimer {
init() {
print("MyTimer.init")
let timer = Timer(timeInterval: 1, repeats: true) {
timer in
print("MyTimer.onTimer")
}
RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
RunLoop.current.run(until: Date(timeIntervalSinceNow: 4.0))
}
}
"MyTimer.onTimer" 5 , ( Perfect) :
$> swift build && ./.build/debug/my-app 8400
Compile Swift Module 'my-app' (7 sources)
Linking ./.build/debug/my-app
MyTimer.init
MyTimer.onTimer
MyTimer.onTimer
MyTimer.onTimer
MyTimer.onTimer
MyTimer.onTimer
[INFO] Starting HTTP server on 0.0.0.0:8181
, . Perfect, , . , , ?