我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停4秒,然后继续执行其余的代码。我该怎么做呢?
我用的是Swift。
我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停4秒,然后继续执行其余的代码。我该怎么做呢?
我用的是Swift。
当前回答
如果你的代码已经在后台线程中运行,在Foundation: thread .sleep(forTimeInterval:)中使用这个方法暂停线程。
例如:
DispatchQueue.global(qos: .userInitiated).async {
// Code is running in a background thread already so it is safe to sleep
Thread.sleep(forTimeInterval: 4.0)
}
(当代码在主线程上运行时,请参阅其他答案以获得建议。)
其他回答
要创建一个简单的时间延迟,您可以导入Darwin,然后使用sleep(秒)来执行延迟。不过,这只需要几秒钟的时间,所以为了更精确的测量,你可以导入Darwin并使用usleep(百万分之一秒)进行非常精确的测量。为了验证这一点,我写道:
import Darwin
print("This is one.")
sleep(1)
print("This is two.")
usleep(400000)
print("This is three.")
打印,然后等待1秒打印,然后等待0.4秒打印。一切都如预期般顺利。
这是添加延迟的一种更简单的方式,不会影响线程执行。
let continueTime: Date = Calendar.current.date(byAdding: .second, value: 30, to: Date())!
while (Date() < continueTime) {
//DO NOTHING
}
如果你的代码已经在后台线程中运行,在Foundation: thread .sleep(forTimeInterval:)中使用这个方法暂停线程。
例如:
DispatchQueue.global(qos: .userInitiated).async {
// Code is running in a background thread already so it is safe to sleep
Thread.sleep(forTimeInterval: 4.0)
}
(当代码在主线程上运行时,请参阅其他答案以获得建议。)
斯威夫特5 <
使用任务。Sleep不会阻塞当前任务以外的任何代码,而且非常简单。
//Delay task by 4 seconds:
Task {
try await Task.sleep(nanoseconds: 4000000000)
//Execute your code here
}
你也可以用Swift 3这样做。
像这样执行延迟后的功能。
override func viewDidLoad() {
super.viewDidLoad()
self.perform(#selector(ClassName.performAction), with: nil, afterDelay: 2.0)
}
@objc func performAction() {
//This function will perform after 2 seconds
print("Delayed")
}