有没有人能告诉我,在Swift 2.2中,几毫秒的睡眠()是怎么用的?
while (true){ print("sleep for 0.002 seconds.") sleep(0.002) // not working}
while (true){
print("sleep for 0.002 seconds.")
sleep(0.002) // not working
}
但
while (true){ print("sleep for 2 seconds.") sleep(2) // working}
print("sleep for 2 seconds.")
sleep(2) // working
它正在发挥作用。
q0qdq0h21#
Usept()占用百万分之一秒的时间
usleep(1000000) //will sleep for 1 secondusleep(2000) //will sleep for .002 seconds
usleep(1000000) //will sleep for 1 second
usleep(2000) //will sleep for .002 seconds
或
let ms = 1000 usleep(useconds_t(2 * ms)) //will sleep for 2 milliseconds (.002 seconds)
let ms = 1000
usleep(useconds_t(2 * ms)) //will sleep for 2 milliseconds (.002 seconds)
let second: Double = 1000000usleep(useconds_t(0.002 * second)) //will sleep for 2 milliseconds (.002 seconds)
let second: Double = 1000000
usleep(useconds_t(0.002 * second)) //will sleep for 2 milliseconds (.002 seconds)
1rhkuytd2#
我认为在当前快速语法中比usleep解决方案更优雅的是:
usleep
Thread.sleep(forTimeInterval: 0.002)
acruukt93#
使用func usleep(_: useconds_t) -> Int32(导入Darwin或Foundation...)
func usleep(_: useconds_t) -> Int32
Darwin
Foundation
重要提示:usleep()占用百万分之一秒,因此usleep(1000000)将休眠1秒
usleep()
usleep(1000000)
csga3l584#
如果你真的需要睡觉,试试@user3441734的答案中建议的usleepe。
然而,你可能会考虑睡眠是否是最好的选择:它就像一个暂停按钮,应用程序在运行时会冻结并没有React。
您可能希望使用NSTimer。
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}
//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
tjvv9vkg5#
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 }}
DispatchQueue.global(qos: .background).async {
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
7dl7o3gd6#
DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) { /*Do something after 0.002 seconds have passed*/}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) {
/*Do something after 0.002 seconds have passed*/
6条答案
按热度按时间q0qdq0h21#
Usept()占用百万分之一秒的时间
或
或
1rhkuytd2#
我认为在当前快速语法中比
usleep
解决方案更优雅的是:acruukt93#
使用
func usleep(_: useconds_t) -> Int32
(导入Darwin
或Foundation
...)重要提示:
usleep()
占用百万分之一秒,因此usleep(1000000)
将休眠1秒csga3l584#
如果你真的需要睡觉,试试@user3441734的答案中建议的
usleep
e。然而,你可能会考虑睡眠是否是最好的选择:它就像一个暂停按钮,应用程序在运行时会冻结并没有React。
您可能希望使用
NSTimer
。tjvv9vkg5#
usept的非阻塞解决方案:
7dl7o3gd6#
或者: