在Swift 2.2中,如何实现几毫秒的睡眠?

wz1wpwve  于 2022-10-04  发布在  Swift
关注(0)|答案(6)|浏览(233)

有没有人能告诉我,在Swift 2.2中,几毫秒的睡眠()是怎么用的?

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

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

它正在发挥作用。

q0qdq0h2

q0qdq0h21#

Usept()占用百万分之一秒的时间

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

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

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

1rhkuytd2#

我认为在当前快速语法中比usleep解决方案更优雅的是:

  1. Thread.sleep(forTimeInterval: 0.002)
acruukt9

acruukt93#

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

重要提示:usleep()占用百万分之一秒,因此usleep(1000000)将休眠1秒

csga3l58

csga3l584#

如果你真的需要睡觉,试试@user3441734的答案中建议的usleepe。

然而,你可能会考虑睡眠是否是最好的选择:它就像一个暂停按钮,应用程序在运行时会冻结并没有React。

您可能希望使用NSTimer

  1. //Declare the timer
  2. var timer = NSTimer.scheduledTimerWithTimeInterval(0.002, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
  3. self, selector: "update", userInfo: nil, repeats: true)
  4. func update() {
  5. // Code here
  6. }
tjvv9vkg

tjvv9vkg5#

usept的非阻塞解决方案:

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

7dl7o3gd6#

或者:

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

相关问题