GCD After

Posted by Genie on April 19, 2021

只适应一个work串行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
typealias Task = () -> Void

var closure: Task?
let workItem = DispatchWorkItem {
    // execute
    closure?()
}

func delay(time: TimeInterval, task: @escaping () -> Void) -> DispatchWorkItem? {
    closure = task
    DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: workItem)
    return workItem
}

func cancleAll() {
    workItem.cancel()
}

delay(time: 2, task: { print("log--1") })
let task = delay(time: 2, task: { print("log--2") })
task?.cancel() // or cancleAll()

适应多Task并行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 typealias Task = (_ cancel: Bool) -> Void

 func delay(time: TimeInterval, task: @escaping () -> Void) -> Task? {
     func dispath_later(block: @escaping () -> Void) {
         DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: block)
     }

     var closure: (() -> Void)? = task
     var result: Task?

     let delayClosure: Task = { cancel in
         if let internalClosure = closure {
             if cancel == false {
                 DispatchQueue.main.async(execute: internalClosure)
             }
         }
         closure = nil
         result = nil
     }

     result = delayClosure

     dispath_later {
         if let delayClosure = result {
             delayClosure(false)
         }
     }

     return result
 }

 func cancle(_ task: Task?) {
     task?(true)
 }

 let task = delay(time: 3, task: { print("log") })
 // cancle(task)