var count = 0
var timer: Timer? = nil
func test() {
let queue = DispatchQueue(label: "aaa")
queue.async {
print("start\(Thread.current)")
queue.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 1), execute: DispatchWorkItem(block: {
print("1s后执行异步任务\(Thread.current)")
}))
self.perform(#selector(self.perfromTask), with: nil, afterDelay: 2)
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
print("定时任务\(Thread.current)")
self.count += 1
if self.count > 10 {
self.timer?.invalidate()
self.timer = nil
}
}
RunLoop.current.add(self.timer!, forMode: .common)
RunLoop.current.run()
}
}
@objc func perfromTask() {
print("perform 延时任务\(Thread.current)")
}
/**
start<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
perform 延时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
1s后执行异步任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)} //(timer任务会卡住当前线程)
*/
网友评论