我翻遍了苹果的iBook,找不到任何关于它的定义:

有人能解释一下dispatch_after的结构吗?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)

更清晰的结构概念:

dispatch_after(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t?)

dispatch_time_t为UInt64。dispatch_queue_t实际上是一个NSObject的类型别名,但是你应该使用你熟悉的GCD方法来获取队列。该区块是一个快速关闭。具体来说,dispatch_block_t定义为()-> Void,相当于()->()。

使用示例:

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    print("test")
}

编辑:

我推荐使用@matt的延时函数。

编辑2:

在Swift 3中,GCD将会有新的包装器。请看这里:https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

原来的例子在Swift 3中是这样写的:

let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    print("test")
}

注意,你可以将deadlineTime声明写为DispatchTime.now() + 1.0,并得到相同的结果,因为+操作符被重写如下(与-类似):

func +(time: DispatchTime, seconds: Double) -> DispatchTime . func +(time: DispatchTime, seconds: Double func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime . func +(time: DispatchWalltime, interval: DispatchTimeInterval

这意味着如果您不使用DispatchTimeInterval enum,而只是写一个数字,则假定您使用的是秒。


斯威夫特 3+

这在Swift 3+中是超级简单和优雅的:

DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
    // ...
}

年长的回答:

为了扩展Cezary的答案,它将在1纳秒后执行,我必须执行以下操作以在4秒半后执行。

let delay = 4.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), block)

编辑:我发现我原来的代码有一点错误。如果不将NSEC_PER_SEC转换为Double类型,隐式类型将导致编译错误。

如果有人能提出一个更优的解决方案,我很乐意听听。


我经常使用dispatch_after,所以我写了一个顶级实用函数来简化语法:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

现在你可以这样说:

delay(0.4) {
    // do stuff
}

哇,一种你可以改进的语言。还有什么比这更好的呢?


更新Swift 3, Xcode 8种子6

看起来几乎不值得费心,现在他们已经改进了调用语法:

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

Matt的语法非常好,如果你需要使块失效,你可能想使用这个:

typealias dispatch_cancelable_closure = (cancel : Bool) -> Void

func delay(time:NSTimeInterval, closure:()->Void) ->  dispatch_cancelable_closure? {

    func dispatch_later(clsr:()->Void) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(time * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), clsr)
    }

    var closure:dispatch_block_t? = closure
    var cancelableClosure:dispatch_cancelable_closure?

    let delayedClosure:dispatch_cancelable_closure = { cancel in
        if closure != nil {
            if (cancel == false) {
                dispatch_async(dispatch_get_main_queue(), closure!);
            }
        }
        closure = nil
        cancelableClosure = nil
    }

    cancelableClosure = delayedClosure

    dispatch_later {
        if let delayedClosure = cancelableClosure {
            delayedClosure(cancel: false)
        }
    }

    return cancelableClosure;
}

func cancel_delay(closure:dispatch_cancelable_closure?) {

    if closure != nil {
        closure!(cancel: true)
    }
}

使用方法如下

let retVal = delay(2.0) {
    println("Later")
}
delay(1.0) {
    cancel_delay(retVal)
}

学分

上面的链接似乎坏了。来自Github的原始Objc代码


另一种方法是像这样扩展Double:

extension Double {
   var dispatchTime: dispatch_time_t {
       get {
           return dispatch_time(DISPATCH_TIME_NOW,Int64(self * Double(NSEC_PER_SEC)))
       }
   }
}

然后你可以这样使用它:

dispatch_after(Double(2.0).dispatchTime, dispatch_get_main_queue(), { () -> Void in
            self.dismissViewControllerAnimated(true, completion: nil)
    })

我喜欢matt的延迟函数,但只是出于偏好,我宁愿限制传递闭包。


Apple为Objective-C提供了dispatch_after代码段:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    <#code to be executed after a specified delay#>
});

以下是移植到Swift 3的相同代码片段:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + <#delayInSeconds#>) {
  <#code to be executed after a specified delay#>
}

使用这段代码在2.0秒后执行一些UI相关的任务。

            let delay = 2.0
            let delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
            let mainQueue = dispatch_get_main_queue()

            dispatch_after(delayInNanoSeconds, mainQueue, {

                print("Some UI related task after delay")
            })

Swift 3.0版本

以下闭包函数在主线程上执行一些延迟后的任务。

func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
       onCompletion()
    })
}

像这样调用这个函数:

performAfterDelay(delay: 4.0) {
  print("test")
}

1)添加这个方法作为UIViewController Extension的一部分。

extension UIViewController{
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue(), block)
    }
}

在VC上调用这个方法:

    self.runAfterDelay(5.0, block: {
     //Add code to this block
        print("run After Delay Success")
    })

2)

performSelector("yourMethod Name", withObject: nil, afterDelay: 1)

3)

override func viewWillAppear(animated: Bool) {

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue(), { () -> () in
    //Code Here
})

/ /紧凑的形式

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue()) {
    //Code here
 }
}

虽然不是OP的原始问题,但某些与NSTimer相关的问题已被标记为该问题的重复,因此值得在这里包含NSTimer的答案。

NSTimer vs dispatch_after

NSTimer更高级,而dispatch_after更低级。 NSTimer更容易取消。取消dispatch_after需要编写更多的代码。

用NSTimer延迟任务

创建一个NSTimer实例。

var timer = NSTimer()

以您需要的延迟启动计时器。

// invalidate the timer if there is any chance that it could have been called before
timer.invalidate()
// delay of 2 seconds
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 

添加一个在延迟之后被调用的函数(使用您用于上面选择器参数的任何名称)。

func delayedAction() {
    print("Delayed action has now started."
}

笔记

如果需要在操作发生之前取消该操作,只需调用timer.invalidate()。 对于重复的动作使用repeats: true。 如果你有一个不需要取消的一次性事件,那么就不需要创建计时器实例变量。以下内容就足够了: NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 在这里看到我更完整的回答。


另一个帮手来延迟你的代码,这是100%的Swift使用,并可选地允许选择一个不同的线程来运行你的延迟代码:

public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
    let dispatchTime = DispatchTime.now() + seconds
    dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}

public enum DispatchLevel {
    case main, userInteractive, userInitiated, utility, background
    var dispatchQueue: DispatchQueue {
        switch self {
        case .main:                 return DispatchQueue.main
        case .userInteractive:      return DispatchQueue.global(qos: .userInteractive)
        case .userInitiated:        return DispatchQueue.global(qos: .userInitiated)
        case .utility:              return DispatchQueue.global(qos: .utility)
        case .background:           return DispatchQueue.global(qos: .background)
        }
    }
}

现在你只需在主线程上延迟你的代码,就像这样:

delay(bySeconds: 1.5) { 
    // delayed code
}

如果你想延迟你的代码到不同的线程:

delay(bySeconds: 1.5, dispatchLevel: .background) { 
    // delayed code that will run on background thread
}

如果你喜欢一个框架,也有一些更方便的功能,然后签出handysswift。你可以通过Carthage将它添加到你的项目中,然后像上面的例子一样使用它,例如:

import HandySwift    

delay(bySeconds: 1.5) { 
    // delayed code
}

在Swift 3.0中

调度队列

  DispatchQueue(label: "test").async {
        //long running Background Task
        for obj in 0...1000 {
            print("async \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.async(execute: { 
            print("UI update on main queue")
        })

    }

    DispatchQueue(label: "m").sync {
        //long running Background Task
        for obj in 0...1000 {
            print("sync \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.sync(execute: {
            print("UI update on main queue")
        })
    }

5秒后调度

    DispatchQueue.main.after(when: DispatchTime.now() + 5) {
        print("Dispatch after 5 sec")
    }

Swift 3.0 & Swift 4.0 & Swift 5.0中最简单的解决方案

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

使用

delayWithSeconds(1) {
   //Do something
}

Swift 3.0版本

以下闭包函数在主线程上执行一些延迟后的任务。

func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
       onCompletion()
    })
}

像这样调用这个函数:

performAfterDelay(delay: 4.0) {
  print("test")
}

这对我很管用。

斯威夫特3:

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

objective - c:

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});

现在在Swift的中央调度(GCD)中异步调度不仅仅是语法糖。

添加Podfile

pod 'AsyncSwift'

然后,你可以这样使用它。

let seconds = 3.0
Async.main(after: seconds) {
print("Is called after 3 seconds")
}.background(after: 6.0) {
print("At least 3.0 seconds after previous block, and 6.0 after Async code is called")
}

我总是喜欢使用扩展而不是自由函数。

斯威夫特4

public extension DispatchQueue {

  private class func delay(delay: TimeInterval, closure: @escaping () -> Void) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
  }

  class func performAction(after seconds: TimeInterval, callBack: @escaping (() -> Void) ) {
    DispatchQueue.delay(delay: seconds) {
      callBack()
    }
  }

}

按以下方法使用。

DispatchQueue.performAction(after: 0.3) {
  // Code Here
}

Swift 4有一个很短的方法来做到这一点:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
    // Your stuff here
    print("hello")
}

Swift 3和4:

您可以在DispatchQueue上创建一个扩展,并在内部添加使用DispatchQueue asyncAfter函数的函数delay

extension DispatchQueue {
    static func delay(_ delay: DispatchTimeInterval, closure: @escaping () -> ()) {
        let timeInterval = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: timeInterval, execute: closure)
    }
}

使用:

DispatchQueue.delay(.seconds(1)) {
    print("This is after delay")
}

在swift中使用asyncAfter延迟GCD调用

let delayQueue = DispatchQueue(label: "com.theappmaker.in", qos: .userInitiated)
let additionalTime: DispatchTimeInterval = .seconds(2)

我们可以延迟为**微秒,毫秒,纳秒

delayQueue.asyncAfter(deadline: .now() + 0.60) {
    print(Date())
}

delayQueue.asyncAfter(deadline: .now() + additionalTime) {
    print(Date())
}

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // ...
});

dispatch_after(_:_:_:)函数有三个参数:

延迟 调度队列 块或闭包

dispatch_after(_:_:_:)函数调用在给定延迟后传递给函数的调度队列上的块或闭包。注意,延迟是使用dispatch_time(_:_:)函数创建的。记住这一点,因为我们在Swift中也使用了这个函数。

我建议你通过Raywenderlich调度教程


对于多个函数使用这个。这对于静态函数或任何UI更新使用动画或活动加载器非常有帮助。

DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
            // Call your function 1
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                // Call your function 2
            }
        }

例如-在tableView重新加载之前使用动画。或任何其他UI更新后的动画。

*// Start your amination* 
self.startAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
                *// The animation will execute depending on the delay time*
                self.stopAnimation()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    *// Now update your view*
                     self.fetchData()
                     self.updateUI()
                }
            }

在Swift 4中

使用以下片段:

    let delayInSec = 1.0
    DispatchQueue.main.asyncAfter(deadline: .now() + delayInSec) {
       // code here
       print("It works")
    }

以下是Swift中asyncAfter的同步版本:

let deadline = DispatchTime.now() + .seconds(3)
let semaphore = DispatchSemaphore.init(value: 0)
DispatchQueue.global().asyncAfter(deadline: deadline) {
    dispatchPrecondition(condition: .onQueue(DispatchQueue.global()))
    semaphore.signal()
}

semaphore.wait()

与异步的一起:

let deadline = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadline) {
    dispatchPrecondition(condition: .onQueue(DispatchQueue.global()))
}

在Swift 5中,在下面使用:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

要在延迟后执行函数或代码,请使用下一个方法

DispatchQueue.main.asyncAfter(deadline: .now() + 'secondsOfDelay') {
        your code here...
    }

在本例中,函数getShowMovies将在1秒后执行

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        self.getShowMovies()
    }

保留当前队列!

除了很好地回答这个问题之外,您还可以考虑保留当前队列以防止不必要的主队列操作(例如,当您试图延迟一些异步操作时)。

func after(_ delay: TimeInterval,
           perform block: @escaping ()->(),
           on queue: DispatchQueue = OperationQueue.current?.underlyingQueue ?? .main) { // So this `queue` preserves the current queue and defaulted to the `main`. Also the caller can pass in the desired queue explicitly
    queue.asyncAfter(deadline: .now() + delay, execute: block)
}

用法:

after(3) {
    // will be executed on the caller's queue
    print(Date())
}