Blame view

HDFwear/Tools/TaskManager.swift 996 Bytes
5507c724   jason   feat:send interval
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
  //
  //  TaskManager.swift
  //  HDFwear
  //
  //  Created by admin on 2024/1/8.
  //
  
  import Foundation
  
  class TaskManager {
      private var lastExecutionTime: DispatchTime = .now()
      private let queue = DispatchQueue(label: "com.watch.taskQueue", attributes: .concurrent)
  
      func executeTaskIfNeeded(taskBlock: @escaping () -> Void) {
          let now = DispatchTime.now()
          let deadline = lastExecutionTime + .milliseconds(300)
  
          let delay: DispatchTimeInterval
          if now >= deadline {
              // If enough time has passed, execute the task immediately
              delay = .seconds(0)
          } else {
              // If not, calculate the delay until the next execution
              delay = .nanoseconds(Int(deadline.uptimeNanoseconds - now.uptimeNanoseconds))
          }
  
          // Schedule the task to execute after the required delay
          lastExecutionTime = .now() + delay
          queue.asyncAfter(deadline: lastExecutionTime) {
              taskBlock()
          }
      }
  }