dispatch_after time triggers immediately

时间秒杀一切 提交于 2019-12-11 08:34:31

问题


This is the first time I've used GCD, I'll admit, so sorry if I've been stupid. I have a dispatch_after command which acts as a handy delay for me.

My problem is that when I send

dispatch_after(500000000000, dispatch_get_main_queue()){
    println("triggered") //or any other code
}

the closure is triggered immediately (e.g. I have tested this and "triggered" prints immediately). It should take longer right? Like 500 seconds longer.

Thanks :)


回答1:


The first parameter of dispatch_after(_:_:_:) is not a delay, but a point in time. From the docs:

when: The temporal milestone returned by dispatch_time or dispatch_walltime.

Discussion This function waits until the specified time and then asynchronously adds block to the specified queue.

You need to construct a delay relative to the current time, using dispatch_time(_:_:):

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(500 * NSEC_PER_SEC))
dispatch_after(delayTime, dispatch_get_main_queue()) { ... }


来源:https://stackoverflow.com/questions/31949034/dispatch-after-time-triggers-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!