Swift 3 Linux with Perfect: add a scheduled interval timer to runLoop

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: #selector(MyTimer.onTimer(timer:)), userInfo: nil, repeats: true)
    }
    @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: #selector(MyTimer.onTimer), userInfo: nil, repeats: true)

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()
    }
}

( 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, , . , , ?

+4
1

Perfect, , Foundation. Perfect Threading: http://www.perfect.org/docs/thread.html

import PerfectThread 
#if os(Linux)
import GlibC
#else
import Darwin
#endif

Threading.dispatch {
  sleep(10) // wait for 10 seconds
  doSomething()
}//end threading


+4

Source: https://habr.com/ru/post/1664893/


All Articles