Last active
May 6, 2019 11:28
-
-
Save Dev1an/06e4bbeb44e0b1b351d5ec3333a361c5 to your computer and use it in GitHub Desktop.
Throttle new tasks down when older tasks are still executing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Throttler.swift | |
| // 3D Viewer | |
| // | |
| // Created by Damiaan on 20/02/2019. | |
| // Copyright © 2019 Devian. All rights reserved. | |
| // | |
| import Dispatch | |
| public class Throttler { | |
| private let group = DispatchGroup() | |
| private let worker = DispatchQueue(label: "Throttle worker", attributes: []) | |
| private let manager = DispatchQueue(label: "Throttle manager", attributes: []) | |
| private var todo: ( () -> Void )? | |
| var notExecuting: Bool { return group.wait(timeout: .now()) == .success } | |
| public func execute(work: @escaping () -> Void) { | |
| manager.sync { todo = work } | |
| if notExecuting { | |
| executeRemainingWork() | |
| } | |
| } | |
| private func executeRemainingWork() { | |
| manager.sync { | |
| group.enter() | |
| if let work = todo { | |
| todo = nil | |
| worker.async { | |
| work() | |
| self.group.leave() | |
| self.executeRemainingWork() | |
| } | |
| } else { | |
| group.leave() | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment