Swift 延时执行

采用 GCD 模式调用:

// 创建目标队列
let workingQueue = dispatch_queue_create( "my_queue" , nil)
 
// 派发到刚创建的队列中,GCD 会负责进行线程调度
dispatch_async(workingQueue) {
     // 在 workingQueue 中异步进行
     println( "努力工作" )
     NSThread.sleepForTimeInterval(2)   // 模拟两秒的执行时间
 
     dispatch_async(dispatch_get_main_queue()) {
         // 返回到主线程更新 UI
         println( "结束工作,更新 UI" )
     }
}

实现延迟调用:

let  time : NSTimeInterval = 2.0
let delay = dispatch_time(DISPATCH_TIME_NOW, 
                          Int64( time  * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
     println( "2 秒后输出" )
}

完整实例:

import Foundation
 
typealias Task = (cancel : Bool) -> ()
 
func delay( time :NSTimeInterval, task:()->()) ->  Task? {
 
     func dispatch_later(block:()->()) {
         dispatch_after(
             dispatch_time(
                 DISPATCH_TIME_NOW, 
                 Int64( time  * Double(NSEC_PER_SEC))),
             dispatch_get_main_queue(),
             block)
     }
 
     var closure: dispatch_block_t? = task
     var result: Task?
 
     let delayedClosure: Task = {
         cancel in
         if  let internalClosure = closure {
             if  (cancel ==  false ) {
                 dispatch_async(dispatch_get_main_queue(), internalClosure);
             }
         }
         closure = nil
         result = nil
     }
 
     result = delayedClosure
 
     dispatch_later {
         if  let delayedClosure = result {
             delayedClosure(cancel:  false )
         }
     }
 
     return  result;
}
 
func cancel(task:Task?) {
     task?(cancel:  true )
}

执行方法

delay(2) { println( "2 秒后输出" ) }


取消方法:

let task = delay(5) { println( "拨打 110" ) }
 
cancel(task)




  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值