简体   繁体   中英

How to Efficiently Schedule Thousands of Async Events Using Swift 3 DispatchQueue

I am moving a map marker 1 metre every 0.1 seconds with the following code:

    for index in 1 ... points.count - 1 {

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 * Double(index)) {
            self.driverMarker.position = points[index]
            self.driverMarker.map = self.mapView
        }

    }

If the distance of all the points is 3000 metres then I set setting 3000 asyncAfters and I am worried this is inefficient.

Is there a better way to do this?

From your requirements stated in the question and comments, I believe using DispatchSourceTimer is better for this task. I provided a sample code for reference below.

var count = 0
var bgTimer: DispatchSourceTimer?

func translateMarker() {
    if count == (points.count - 1) {
        bgTimer?.cancel()
        bgTimer = nil
        return
    }
    self.driverMarker.position = points[index]
    self.driverMarker.map = self.mapView
    count += 1
}

override func viewDidLoad() {
    super.viewDidLoad()

    let queue:DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)

    bgTimer = DispatchSource.makeTimerSource(flags: [], queue: queue)
    bgTimer?.scheduleRepeating(deadline: DispatchTime.now(), interval: 0.1)

    bgTimer?.setEventHandler(handler: {
        self.translateMarker()
    })

    bgTimer?.resume()
}

Please let me know if you are facing any issues in implementing this. Feel free to suggest edits to make this better :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM