如何在swift 2.2中睡几毫秒?

时间:2016-06-30 09:56:41

标签: swift uikit sleep

请有人告诉我如何在swift 2.2中使用sleep()几毫秒?

while (true){
    print("sleep for 0.002 seconds.")
    sleep(0.002) // not working
}

while (true){
    print("sleep for 2 seconds.")
    sleep(2) // working
}

它正在运作。

6 个答案:

答案 0 :(得分:72)

usleep()花费百万分之一秒

usleep(1000000) //will sleep for 1 second
usleep(2000) //will sleep for .002 seconds

OR

 let ms = 1000
 usleep(useconds_t(2 * ms)) //will sleep for 2 milliseconds (.002 seconds)

OR

let second: Double = 1000000
usleep(useconds_t(0.002 * second)) //will sleep for 2 milliseconds (.002 seconds)

答案 1 :(得分:8)

使用func usleep(_: useconds_t) -> Int32(导入DarwinFoundation ...)

答案 2 :(得分:7)

在目前的快速语法中,我认为比usleep解决方案更优雅的是: Thread.sleep(forTimeInterval: 0.002)

答案 3 :(得分:4)

如果您真的需要睡觉,请按照@ user3441734的回答中的建议尝试usleep

但是,您可能希望考虑睡眠是否是最佳选择:它就像一个暂停按钮,应用程序将在运行时冻结并无响应。

您可能希望使用NSTimer

 //Declare the timer
 var timer = NSTimer.scheduledTimerWithTimeInterval(0.002, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
 self, selector: "update", userInfo: nil, repeats: true)



func update() {
    // Code here
}

答案 4 :(得分:0)

或者:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) {
   /*Do something after 0.002 seconds have passed*/
}

答案 5 :(得分:0)

用于usleep的非阻塞解决方案:

DispatchQueue.global(qos: .background).async {
    let second: Double = 1000000
    usleep(useconds_t(0.002 * second)) 
    print("Active after 0.002 sec, and doesn't block main")
    DispatchQueue.main.async{
        //do stuff in the main thread here
    }
}