加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:38:10 所属栏目:百科 来源:网络整理
导读:我正在尝试使用 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.s
我正在尝试使用 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读