微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift 3 Linux with Perfect:在runLoop中添加一个带间隔的预定计时器

我正在尝试使用 Perfect library在我的Ubuntu(Ubuntu 15.10 wily,Swift swift-3.0.1-RELEASE)上使用Swift创建一个应用程序.

我希望每X秒都有一个函数.为此,我使用的是Timer class of the Foundation module

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

尽管使用此代码找到了几个解决方案,但编译失败了:

$> 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) {

如果我从NSObject扩展我的类或者我删除了参数计时器,则会出现另一个编译错误

$> 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,selector: #selector(MyTimer.onTimer),repeats: true)

我试图使用不使用选择器的其他声明:

class MyTimer {
    init() {
        print("MyTimer.init")
        var timer = Timer.scheduledTimer(withTimeInterval: 1,repeats: true) {
            timer in
            print("MyTimer.onTimer")
        }
    }
}

编译工作,但我的第二次打印从未被调用.我还尝试手动将我的计时器添加到当前的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,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,请不要使用Foundation内容.尝试完美线程: 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

它安全而简单非常典型的服务器端编码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐